diff --git a/src/AutoRest.CSharp/Common/AutoRest/Plugins/CSharpGen.cs b/src/AutoRest.CSharp/Common/AutoRest/Plugins/CSharpGen.cs index 0661338ae45..2e3bcdb1660 100644 --- a/src/AutoRest.CSharp/Common/AutoRest/Plugins/CSharpGen.cs +++ b/src/AutoRest.CSharp/Common/AutoRest/Plugins/CSharpGen.cs @@ -44,8 +44,6 @@ public async Task ExecuteAsync(CodeModel codeModel) var inputNamespace = new CodeModelConverter(codeModel, schemaUsageProvider).CreateNamespace(); MgmtContext.Initialize(new BuildContext(inputNamespace, sourceInputModel)); await MgmtTarget.ExecuteAsync(project); - if (Configuration.MgmtTestConfiguration is not null && !Configuration.MgmtConfiguration.MgmtDebug.ReportOnly) - await MgmtTestTarget.ExecuteAsync(project, inputNamespace, sourceInputModel); GenerateMgmtReport(project); } else @@ -88,8 +86,6 @@ public async Task ExecuteAsync(InputNamespace rootNamesp InputNamespaceTransformer.Transform(rootNamespace); MgmtContext.Initialize(new BuildContext(rootNamespace, sourceInputModel)); await MgmtTarget.ExecuteAsync(project); - if (Configuration.GenerateSampleProject) - await MgmtTestTarget.ExecuteAsync(project, rootNamespace, sourceInputModel); } else { diff --git a/src/AutoRest.CSharp/Common/Input/CodeModelConverter.cs b/src/AutoRest.CSharp/Common/Input/CodeModelConverter.cs index cf16a4d5045..c4c595b8754 100644 --- a/src/AutoRest.CSharp/Common/Input/CodeModelConverter.cs +++ b/src/AutoRest.CSharp/Common/Input/CodeModelConverter.cs @@ -193,13 +193,49 @@ private InputOperation CreateOperation(ServiceRequest serviceRequest, Operation return result; } + private static InputExampleValue HandleRawExampleValue(InputType inputType, object? rawValue) + { + if (rawValue == null) + { + return InputExampleValue.Null(inputType); + } + var type = rawValue.GetType(); + if (type.IsGenericType) + { + // handle dictionary + if (type == typeof(Dictionary)) + { + var values = new Dictionary(); + foreach (var (key, value) in (Dictionary)rawValue) + { + // key is always a string + // since we do not have a schema for the value type here, we use unknown + values.Add((string)key, HandleRawExampleValue(InputPrimitiveType.Unknown, value)); + } + return new InputExampleObjectValue(inputType, values); + } + // handle list + if (type == typeof(List)) + { + var values = new List(); + foreach (var item in (List)rawValue) + { + values.Add(HandleRawExampleValue(InputPrimitiveType.Unknown, item)); + } + return new InputExampleListValue(inputType, values); + } + } + + // the deserialization part of the test modeler output has a bug that all the primitive types are deserialized as strings, here we should convert them according to its real type + return new InputExampleRawValue(inputType, ConvertRawValue(inputType, rawValue)); + } + private InputExampleValue CreateExampleValue(ExampleValue exampleValue) { var inputType = CreateType(exampleValue.Schema, exampleValue.Schema.Extensions?.Format, false); if (exampleValue.RawValue != null) { - // test modeler has a bug that all the primitive types are deserialized as strings, here we should convert them according to its real type - return new InputExampleRawValue(inputType, ConvertRawValue(inputType, exampleValue.RawValue)); + return HandleRawExampleValue(inputType, exampleValue.RawValue); } if (exampleValue.Elements != null && exampleValue.Elements.Any()) { diff --git a/src/AutoRest.CSharp/LowLevel/Extensions/Snippets.ExampleValues.cs b/src/AutoRest.CSharp/Common/Output/Expressions/Samples/Snippets.ExampleValues.cs similarity index 91% rename from src/AutoRest.CSharp/LowLevel/Extensions/Snippets.ExampleValues.cs rename to src/AutoRest.CSharp/Common/Output/Expressions/Samples/Snippets.ExampleValues.cs index 112756b0ad4..26e9a544760 100644 --- a/src/AutoRest.CSharp/LowLevel/Extensions/Snippets.ExampleValues.cs +++ b/src/AutoRest.CSharp/Common/Output/Expressions/Samples/Snippets.ExampleValues.cs @@ -12,16 +12,18 @@ using AutoRest.CSharp.Common.Output.Expressions.KnownValueExpressions; using AutoRest.CSharp.Common.Output.Expressions.ValueExpressions; using AutoRest.CSharp.Generation.Types; +using AutoRest.CSharp.Output.Builders; using AutoRest.CSharp.Output.Models.Serialization; using AutoRest.CSharp.Output.Models.Types; using AutoRest.CSharp.Output.Samples.Models; using AutoRest.CSharp.Utilities; using Azure; using Azure.Core; +using Azure.ResourceManager.Models; using Microsoft.CodeAnalysis.CSharp; using static AutoRest.CSharp.Common.Output.Models.Snippets; -namespace AutoRest.CSharp.LowLevel.Extensions +namespace AutoRest.CSharp.Common.Output.Models.Samples { internal static partial class ExampleValueSnippets { @@ -188,13 +190,35 @@ private static ValueExpression GetExpressionForFrameworkType(Type frameworkType, return Null.CastTo(frameworkType); } - return frameworkType.IsValueType ? Default.CastTo(frameworkType) : Null.CastTo(frameworkType); + // TODO -- this might be an issue. We have so many shared common types in resoucemanager which replace the generated types in a library. + // This way is only temporary, we need a universal way to handle those replaced types. + if (frameworkType == typeof(ManagedServiceIdentityType)) + { + if (exampleValue is InputExampleRawValue rawValue && rawValue.RawValue is string str) + { + return Literal(str); + } + + return Default.CastTo(frameworkType); + } + + if (frameworkType == typeof(UserAssignedIdentity)) + { + return New.Instance(frameworkType); + } + + return DefaultOf(frameworkType); } - public static ValueExpression GetExpression(InputExampleParameterValue exampleParameterValue, SerializationFormat serializationFormat) + public static ValueExpression GetExpression(CSharpType type, InputExampleValue? value) + => value != null ? + GetExpression(type, value, SerializationBuilder.GetDefaultSerializationFormat(type)) : + DefaultOf(type); + + public static ValueExpression GetExpression(ExampleParameterValue exampleParameterValue, SerializationFormat serializationFormat) { if (exampleParameterValue.Value != null) - return GetExpression(exampleParameterValue.Type, exampleParameterValue.Value, serializationFormat); + return GetExpression(exampleParameterValue.Type, exampleParameterValue.Value, serializationFormat == SerializationFormat.Default ? SerializationBuilder.GetDefaultSerializationFormat(exampleParameterValue.Type) : serializationFormat); else if (exampleParameterValue.Expression != null) return exampleParameterValue.Expression; else @@ -373,12 +397,12 @@ private static ValueExpression GetExpressionForObjectType(ObjectType objectType, if (valueDict.TryGetValue(property.InputModelProperty!.SerializedName, out var exampleValue)) { properties.Remove(property); - argument = GetExpression(propertyType, exampleValue, property.SerializationFormat, includeCollectionInitialization: true); + argument = GetExpression(propertyType, exampleValue, GetSerializationFormat(property, propertyType), includeCollectionInitialization: true); } else { // if no match, we put default here - argument = propertyType.IsValueType && !propertyType.IsNullable ? Default : Null; + argument = DefaultOf(propertyType); } arguments.Add(argument); } @@ -390,13 +414,24 @@ private static ValueExpression GetExpressionForObjectType(ObjectType objectType, foreach (var (property, exampleValue) in propertiesToWrite) { // we need to pass in the current type of this property to make sure its initialization is correct - var propertyExpression = GetExpression(property.Declaration.Type, exampleValue, property.SerializationFormat, includeCollectionInitialization: false); + var propertyExpression = GetExpression(property.Declaration.Type, exampleValue, GetSerializationFormat(property, property.Declaration.Type), includeCollectionInitialization: false); initializerDict.Add(property.Declaration.Name, propertyExpression); } objectPropertyInitializer = new(initializerDict, false); } return new NewInstanceExpression(objectType.Type, arguments, objectPropertyInitializer); + + static SerializationFormat GetSerializationFormat(ObjectTypeProperty property, CSharpType propertyType) + { + var serializationFormat = property.SerializationFormat; // this works for typespec input models + // TODO - wait for fix. For swagger input models, the serialization format is not properly added onto the property, therefore here we have to find the serialization format again + if (serializationFormat == SerializationFormat.Default) + { + serializationFormat = SerializationBuilder.GetDefaultSerializationFormat(propertyType); + } + return serializationFormat; + } } private static IReadOnlyDictionary GetPropertiesToWrite(IEnumerable properties, IReadOnlyDictionary valueDict) diff --git a/src/AutoRest.CSharp/Common/Output/Expressions/Snippets.DeclarationStatements.cs b/src/AutoRest.CSharp/Common/Output/Expressions/Snippets.DeclarationStatements.cs index 8716ddb6131..f43edbc1096 100644 --- a/src/AutoRest.CSharp/Common/Output/Expressions/Snippets.DeclarationStatements.cs +++ b/src/AutoRest.CSharp/Common/Output/Expressions/Snippets.DeclarationStatements.cs @@ -4,7 +4,6 @@ using System; using AutoRest.CSharp.Common.Output.Expressions.KnownValueExpressions; using AutoRest.CSharp.Common.Output.Expressions.KnownValueExpressions.Azure; -using AutoRest.CSharp.Common.Output.Expressions.KnownValueExpressions.System; using AutoRest.CSharp.Common.Output.Expressions.Statements; using AutoRest.CSharp.Common.Output.Expressions.ValueExpressions; using AutoRest.CSharp.Generation.Types; diff --git a/src/AutoRest.CSharp/Common/Output/Expressions/Snippets.cs b/src/AutoRest.CSharp/Common/Output/Expressions/Snippets.cs index 7bba6e7be97..96a9f090b92 100644 --- a/src/AutoRest.CSharp/Common/Output/Expressions/Snippets.cs +++ b/src/AutoRest.CSharp/Common/Output/Expressions/Snippets.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Reflection; -using System.Text.Json; using AutoRest.CSharp.Common.Input; using AutoRest.CSharp.Common.Output.Expressions; using AutoRest.CSharp.Common.Output.Expressions.KnownValueExpressions; @@ -14,7 +12,6 @@ using AutoRest.CSharp.Generation.Types; using AutoRest.CSharp.Generation.Writers; using AutoRest.CSharp.Output.Models.Types; -using static AutoRest.CSharp.Common.Input.Configuration; namespace AutoRest.CSharp.Common.Output.Models { diff --git a/src/AutoRest.CSharp/Common/Output/Expressions/Statements/InvokeInstanceMethodStatement.cs b/src/AutoRest.CSharp/Common/Output/Expressions/Statements/InvokeInstanceMethodStatement.cs index de988f54236..f327dc1b23d 100644 --- a/src/AutoRest.CSharp/Common/Output/Expressions/Statements/InvokeInstanceMethodStatement.cs +++ b/src/AutoRest.CSharp/Common/Output/Expressions/Statements/InvokeInstanceMethodStatement.cs @@ -8,16 +8,18 @@ namespace AutoRest.CSharp.Common.Output.Expressions.Statements { - internal record InvokeInstanceMethodStatement(ValueExpression? InstanceReference, string MethodName, IReadOnlyList Arguments, bool CallAsAsync) : MethodBodyStatement + internal record InvokeInstanceMethodStatement(ValueExpression? InstanceReference, string MethodName, IReadOnlyList Arguments, bool CallAsAsync, bool AddConfigureAwaitFalse = true) : MethodBodyStatement { public InvokeInstanceMethodStatement(ValueExpression? instance, string methodName) : this(instance, methodName, Array.Empty(), false) { } public InvokeInstanceMethodStatement(ValueExpression? instance, string methodName, ValueExpression arg) : this(instance, methodName, new[] { arg }, false) { } public InvokeInstanceMethodStatement(ValueExpression? instance, string methodName, ValueExpression arg1, ValueExpression arg2) : this(instance, methodName, new[] { arg1, arg2 }, false) { } public InvokeInstanceMethodStatement(ValueExpression? instance, string methodName, ValueExpression arg1, ValueExpression arg2, ValueExpression arg3) : this(instance, methodName, new[] { arg1, arg2, arg3 }, false) { } + public InvokeInstanceMethodStatement(InvokeInstanceMethodExpression expression) : this(expression.InstanceReference, expression.MethodName, expression.Arguments, expression.CallAsAsync, expression.AddConfigureAwaitFalse) { } + public sealed override void Write(CodeWriter writer) { - new InvokeInstanceMethodExpression(InstanceReference, MethodName, Arguments, null, CallAsAsync).Write(writer); + new InvokeInstanceMethodExpression(InstanceReference, MethodName, Arguments, null, CallAsAsync, AddConfigureAwaitFalse).Write(writer); writer.LineRaw(";"); } } diff --git a/src/AutoRest.CSharp/Common/Output/Expressions/Statements/SingleLineCommentStatement.cs b/src/AutoRest.CSharp/Common/Output/Expressions/Statements/SingleLineCommentStatement.cs index 1f83292a114..e005ab4c39d 100644 --- a/src/AutoRest.CSharp/Common/Output/Expressions/Statements/SingleLineCommentStatement.cs +++ b/src/AutoRest.CSharp/Common/Output/Expressions/Statements/SingleLineCommentStatement.cs @@ -10,4 +10,9 @@ internal record SingleLineCommentStatement(FormattableString Message) : MethodBo { public SingleLineCommentStatement(string message) : this(FormattableStringHelpers.FromString(message)) { } + + public override void Write(CodeWriter writer) + { + writer.Line($"// {Message}"); + } } diff --git a/src/AutoRest.CSharp/MgmtTest/Models/ExampleParameterValue.cs b/src/AutoRest.CSharp/Common/Output/Models/Samples/ExampleParameterValue.cs similarity index 62% rename from src/AutoRest.CSharp/MgmtTest/Models/ExampleParameterValue.cs rename to src/AutoRest.CSharp/Common/Output/Models/Samples/ExampleParameterValue.cs index d90e8fd781d..1255f1a9195 100644 --- a/src/AutoRest.CSharp/MgmtTest/Models/ExampleParameterValue.cs +++ b/src/AutoRest.CSharp/Common/Output/Models/Samples/ExampleParameterValue.cs @@ -1,21 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -using System; using AutoRest.CSharp.Common.Input.Examples; +using AutoRest.CSharp.Common.Output.Expressions.ValueExpressions; using AutoRest.CSharp.Generation.Types; -using AutoRest.CSharp.Input; using AutoRest.CSharp.Output.Models.Requests; using AutoRest.CSharp.Output.Models.Shared; -namespace AutoRest.CSharp.MgmtTest.Models +namespace AutoRest.CSharp.Output.Samples.Models { /// - /// A represents a value for a parameter, which could either be a , or a as a literal + /// A represents a value for a parameter, which could either be a , or a as an expression /// - /// - /// - /// internal record ExampleParameterValue { public string Name { get; } @@ -24,7 +20,7 @@ internal record ExampleParameterValue public InputExampleValue? Value { get; } - public FormattableString? Expression { get; } + public ValueExpression? Expression { get; } private ExampleParameterValue(string name, CSharpType type) { @@ -37,9 +33,9 @@ public ExampleParameterValue(Reference reference, InputExampleValue value) : thi Value = value; } - public ExampleParameterValue(Reference reference, FormattableString rawValue) : this(reference.Name, reference.Type) + public ExampleParameterValue(Reference reference, ValueExpression expression) : this(reference.Name, reference.Type) { - Expression = rawValue; + Expression = expression; } public ExampleParameterValue(Parameter parameter, InputExampleValue value) : this(parameter.Name, parameter.Type) @@ -47,9 +43,9 @@ public ExampleParameterValue(Parameter parameter, InputExampleValue value) : thi Value = value; } - public ExampleParameterValue(Parameter parameter, FormattableString rawValue) : this(parameter.Name, parameter.Type) + public ExampleParameterValue(Parameter parameter, ValueExpression expression) : this(parameter.Name, parameter.Type) { - Expression = rawValue; + Expression = expression; } } } diff --git a/src/AutoRest.CSharp/LowLevel/Output/Samples/DpgOperationSample.cs b/src/AutoRest.CSharp/LowLevel/Output/Samples/DpgOperationSample.cs index af19619ecae..1d427f1a072 100644 --- a/src/AutoRest.CSharp/LowLevel/Output/Samples/DpgOperationSample.cs +++ b/src/AutoRest.CSharp/LowLevel/Output/Samples/DpgOperationSample.cs @@ -10,8 +10,8 @@ using AutoRest.CSharp.Common.Input.Examples; using AutoRest.CSharp.Common.Output.Expressions.Statements; using AutoRest.CSharp.Common.Output.Expressions.ValueExpressions; +using AutoRest.CSharp.Common.Output.Models.Samples; using AutoRest.CSharp.Generation.Types; -using AutoRest.CSharp.LowLevel.Extensions; using AutoRest.CSharp.Output.Models; using AutoRest.CSharp.Output.Models.Shared; using AutoRest.CSharp.Output.Models.Types; @@ -100,7 +100,7 @@ public IEnumerable GetValueExpressionsForParameters(IEnumerable if (parameter.IsOptionalInSignature) continue; - parameterExpression = parameter.Type.IsValueType && !parameter.Type.IsNullable ? Default.CastTo(parameter.Type) : Null.CastTo(parameter.Type); + parameterExpression = DefaultOf(parameter.Type); } if (IsInlineParameter(parameter)) { @@ -117,12 +117,12 @@ public IEnumerable GetValueExpressionsForParameters(IEnumerable } } - private Dictionary? _parameterValueMapping; - public Dictionary ParameterValueMapping => _parameterValueMapping ??= EnsureParameterValueMapping(); + private Dictionary? _parameterValueMapping; + public Dictionary ParameterValueMapping => _parameterValueMapping ??= EnsureParameterValueMapping(); - private Dictionary EnsureParameterValueMapping() + private Dictionary EnsureParameterValueMapping() { - var result = new Dictionary(); + var result = new Dictionary(); var parameters = GetAllParameters(); var parameterExamples = GetAllParameterExamples(); @@ -139,14 +139,14 @@ private Dictionary EnsureParameterValueMappi if (!parameter.IsOptionalInSignature) { ValueExpression parameterExpression = parameter.Type.IsValueType && !parameter.Type.IsNullable ? Default.CastTo(parameter.Type) : Null.CastTo(parameter.Type); - result.Add(parameter.Name, new InputExampleParameterValue(parameter, parameterExpression)); + result.Add(parameter.Name, new ExampleParameterValue(parameter, parameterExpression)); } // if it is optional, we just do not put it in the map indicates that in the invocation we could omit it } else { // add it into the mapping - result.Add(parameter.Name, new InputExampleParameterValue(parameter, exampleValue)); + result.Add(parameter.Name, new ExampleParameterValue(parameter, exampleValue)); } } @@ -202,11 +202,11 @@ private IEnumerable GetAllParameterExamples() } } - private bool ProcessKnownParameters(Dictionary result, Parameter parameter) + private bool ProcessKnownParameters(Dictionary result, Parameter parameter) { if (parameter == KnownParameters.WaitForCompletion) { - result.Add(parameter.Name, new InputExampleParameterValue(parameter, new TypeReference(typeof(WaitUntil)).Property(nameof(WaitUntil.Completed)))); + result.Add(parameter.Name, new ExampleParameterValue(parameter, new TypeReference(typeof(WaitUntil)).Property(nameof(WaitUntil.Completed)))); return true; } @@ -219,41 +219,41 @@ private bool ProcessKnownParameters(Dictionary - /// A represents a value for a parameter, which could either be a , or a as a literal - /// - internal record InputExampleParameterValue - { - public string Name { get; } - - public CSharpType Type { get; } - - public InputExampleValue? Value { get; } - - public ValueExpression? Expression { get; } - - private InputExampleParameterValue(string name, CSharpType type) - { - Name = name; - Type = type; - } - - public InputExampleParameterValue(Reference reference, InputExampleValue value) : this(reference.Name, reference.Type) - { - Value = value; - } - - public InputExampleParameterValue(Reference reference, ValueExpression expression) : this(reference.Name, reference.Type) - { - Expression = expression; - } - - public InputExampleParameterValue(Parameter parameter, InputExampleValue value) : this(parameter.Name, parameter.Type) - { - Value = value; - } - - public InputExampleParameterValue(Parameter parameter, ValueExpression expression) : this(parameter.Name, parameter.Type) - { - Expression = expression; - } - } -} diff --git a/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtConfiguration.cs b/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtConfiguration.cs index e4f8a084dcd..7f4609fe23e 100644 --- a/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtConfiguration.cs +++ b/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtConfiguration.cs @@ -350,6 +350,7 @@ internal void SaveConfiguration(Utf8JsonWriter writer) WriteNonEmptySettings(writer, nameof(PrivilegedOperations), PrivilegedOperations); WriteNonEmptySettings(writer, nameof(OverrideOperationName), OverrideOperationName); WriteNonEmptySettings(writer, nameof(PartialResources), PartialResources); + WriteNonEmptySettings(writer, nameof(RawParameterizedScopes), RawParameterizedScopes); MgmtDebug.Write(writer, nameof(MgmtDebug)); if (IsArmCore) writer.WriteBoolean("ArmCore", IsArmCore); diff --git a/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtOutputLibrary.cs b/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtOutputLibrary.cs index d692cf0f0dd..389163e81d2 100644 --- a/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtOutputLibrary.cs +++ b/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtOutputLibrary.cs @@ -21,6 +21,7 @@ using Azure.Core; using System.Runtime.CompilerServices; using AutoRest.CSharp.Common.Input.InputTypes; +using AutoRest.CSharp.Mgmt.Output.Samples; namespace AutoRest.CSharp.Mgmt.AutoRest { @@ -118,6 +119,9 @@ public MgmtOutputLibrary(InputNamespace inputNamespace) // initialize the property bag collection // TODO -- considering provide a customized comparer PropertyBagModels = new HashSet(); + + // initialize the samples + SampleProviders = new Lazy>(() => EnsureMgmtClientSampleProviders().ToArray()); } private Dictionary EnsureSchemaNameToModels() => _schemaToModels.ToDictionary(kv => kv.Key.Name, kv => kv.Value); @@ -954,6 +958,21 @@ private Dictionary PopulateOperationsToRequestPaths return operationsToRequestPath; } + private IEnumerable EnsureMgmtClientSampleProviders() + { + IEnumerable providers = ArmResources.Cast().Concat(ResourceCollections).Concat(Extensions); + foreach (var provider in providers) + { + var sampleProvider = new MgmtSampleProvider(Configuration.Namespace, provider, MgmtContext.Context.SourceInputModel); + if (!sampleProvider.IsEmpty) + { + yield return sampleProvider; + } + } + } + + public Lazy> SampleProviders { get; } + private class ObjectReferenceEqualityComparer : EqualityComparer where T : class { public override bool Equals(T? x, T? y) => ReferenceEquals(x, y); diff --git a/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtTarget.cs b/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtTarget.cs index 1e533fbfdbb..368f7c25747 100644 --- a/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtTarget.cs +++ b/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtTarget.cs @@ -4,10 +4,11 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.IO; using System.Linq; using System.Threading.Tasks; -using AutoRest.CSharp.Common.Utilities; using AutoRest.CSharp.Common.Input; +using AutoRest.CSharp.Common.Utilities; using AutoRest.CSharp.Generation.Writers; using AutoRest.CSharp.Mgmt.AutoRest; using AutoRest.CSharp.Mgmt.AutoRest.PostProcess; @@ -236,6 +237,18 @@ public static async Task ExecuteAsync(GeneratedCodeWorkspace project) var modelsToKeep = Configuration.MgmtConfiguration.KeepOrphanedModels.ToImmutableHashSet(); await project.PostProcessAsync(new MgmtPostProcessor(modelsToKeep, modelFactoryProvider?.FullName)); + + // write samples if enabled + if (Configuration.MgmtTestConfiguration?.Sample ?? Configuration.GenerateSampleProject) + { + string sampleOutputFolder = GetSampleOutputFolder(SAMPLE_DEFAULT_OUTPUT_PATH); + foreach (var sampleProvider in MgmtContext.Library.SampleProviders.Value) + { + var sampleWriter = new CodeWriter(); + new ExpressionTypeProviderWriter(sampleWriter, sampleProvider).Write(); + project.AddGeneratedTestFile(Path.Combine(sampleOutputFolder, $"Samples/{sampleProvider.Type.Name}.cs"), sampleWriter.ToString()); + } + } } private static void WriteExtensions(GeneratedCodeWorkspace project, bool isArmCore, MgmtExtensionWrapper extensionWrapper, IEnumerable extensions, IEnumerable mockableExtensions) @@ -300,5 +313,33 @@ private static void WriteSerialization(GeneratedCodeWorkspace project, TypeProvi serializeWriter.WriteSerialization(serializerCodeWriter, model); AddGeneratedFile(project, serializationFileName, serializerCodeWriter.ToString()); } + + private const string SOURCE_DEFAULT_OUTPUT_PATH = $"/src/Generated"; + private const string MOCK_TEST_DEFAULT_OUTPUT_PATH = "/tests/Generated"; + private const string SAMPLE_DEFAULT_OUTPUT_PATH = "/samples/Generated"; + + private static string GetSampleOutputFolder(string defaultOutputPath) + { + if (!string.IsNullOrEmpty(Configuration.MgmtTestConfiguration?.OutputFolder)) + return Configuration.MgmtTestConfiguration.OutputFolder; + + string folder = FormatPath(Configuration.OutputFolder); + // if the output folder is not given explicitly, try to figure it out from general output folder if possible according to default folder structure: + // Azure.ResourceManager.XXX \ src \ Generated <- default sdk source output folder + // \ samples(or tests) \ Generated <- default sample output folder defined in msbuild + if (folder.EndsWith(SOURCE_DEFAULT_OUTPUT_PATH, StringComparison.InvariantCultureIgnoreCase)) + return Path.Combine(folder, $"../../{defaultOutputPath}"); + else if (folder.EndsWith(SAMPLE_DEFAULT_OUTPUT_PATH, StringComparison.InvariantCultureIgnoreCase) || folder.EndsWith(MOCK_TEST_DEFAULT_OUTPUT_PATH, StringComparison.InvariantCultureIgnoreCase)) + return folder; + else + throw new InvalidOperationException("'sample-gen.output-folder' is not configured and can't figure it out from give general output-folder"); + } + + private static string FormatPath(string? path) + { + if (string.IsNullOrEmpty(path)) + return path ?? ""; + return Path.GetFullPath(path.TrimEnd('/', '\\')).Replace("\\", "/"); + } } } diff --git a/src/AutoRest.CSharp/MgmtTest/AutoRest/MgmtTestConfiguration.cs b/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtTestConfiguration.cs similarity index 77% rename from src/AutoRest.CSharp/MgmtTest/AutoRest/MgmtTestConfiguration.cs rename to src/AutoRest.CSharp/Mgmt/AutoRest/MgmtTestConfiguration.cs index b07ad58ccc4..86332f05d68 100644 --- a/src/AutoRest.CSharp/MgmtTest/AutoRest/MgmtTestConfiguration.cs +++ b/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtTestConfiguration.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text.Json; using AutoRest.CSharp.AutoRest.Communication; @@ -24,7 +25,6 @@ internal class MgmtTestConfiguration public MgmtTestConfiguration( IReadOnlyList skippedOperations, JsonElement? sourceCodePath = default, - JsonElement? mock = default, JsonElement? sample = default, JsonElement? outputFolder = default, JsonElement? clearOutputFolder = default) @@ -43,11 +43,11 @@ public MgmtTestConfiguration( if (testGenRoot.ValueKind != JsonValueKind.Object) return null; - testGenRoot.TryGetProperty(nameof(SkippedOperations), out var skippedOperationsElement); - testGenRoot.TryGetProperty(nameof(SourceCodePath), out var sourceCodePath); - testGenRoot.TryGetProperty(nameof(Sample), out var sample); - testGenRoot.TryGetProperty(nameof(OutputFolder), out var testGenOutputFolder); - testGenRoot.TryGetProperty(nameof(ClearOutputFolder), out var testGenClearOutputFolder); + testGenRoot.TryGetProperty(Options.SkippedOperations, out var skippedOperationsElement); + testGenRoot.TryGetProperty(Options.SourcePath, out var sourceCodePath); + testGenRoot.TryGetProperty(Options.Sample, out var sample); + testGenRoot.TryGetProperty(Options.OutputFolder, out var testGenOutputFolder); + testGenRoot.TryGetProperty(Options.ClearOutputFolder, out var testGenClearOutputFolder); var skippedOperations = Configuration.DeserializeArray(skippedOperationsElement); @@ -67,23 +67,41 @@ public MgmtTestConfiguration( return new MgmtTestConfiguration( skippedOperations: autoRest.GetValue(string.Format(TestGenOptionsFormat, "skipped-operations")).GetAwaiter().GetResult() ?? Array.Empty(), sourceCodePath: autoRest.GetValue(string.Format(TestGenOptionsFormat, "source-path")).GetAwaiter().GetResult(), - mock: autoRest.GetValue(string.Format(TestGenOptionsFormat, "mock")).GetAwaiter().GetResult(), sample: autoRest.GetValue(string.Format(TestGenOptionsFormat, "sample")).GetAwaiter().GetResult(), outputFolder: autoRest.GetValue(string.Format(TestGenOptionsFormat, "output-folder")).GetAwaiter().GetResult(), clearOutputFolder: autoRest.GetValue(string.Format(TestGenOptionsFormat, "clear-output-folder")).GetAwaiter().GetResult()); } + private static class Options + { + internal const string SkippedOperations = "skipped-operations"; + + internal const string SourcePath = "source-path"; + + internal const string Sample = "sample"; + + internal const string OutputFolder = "output-folder"; + + internal const string ClearOutputFolder = "clear-output-folder"; + } + internal void SaveConfiguration(Utf8JsonWriter writer) { writer.WriteStartObject(TestGenOptionsRoot); - WriteNonEmptySettings(writer, nameof(SkippedOperations), SkippedOperations); + WriteNonEmptySettings(writer, Options.SkippedOperations, SkippedOperations); if (SourceCodePath is not null) - writer.WriteString(nameof(SourceCodePath), SourceCodePath); + writer.WriteString(Options.SourcePath, SourceCodePath); if (Sample) - writer.WriteBoolean(nameof(Sample), Sample); + writer.WriteBoolean(Options.Sample, Sample); + + if (OutputFolder is not null) + writer.WriteString(Options.OutputFolder, Path.GetRelativePath(Configuration.OutputFolder, OutputFolder)); + + if (!ClearOutputFolder) + writer.WriteBoolean(Options.ClearOutputFolder, ClearOutputFolder); writer.WriteEndObject(); } diff --git a/src/AutoRest.CSharp/Mgmt/Models/MgmtClientOperation.cs b/src/AutoRest.CSharp/Mgmt/Models/MgmtClientOperation.cs index e5d1e25d96e..6b0582494ef 100644 --- a/src/AutoRest.CSharp/Mgmt/Models/MgmtClientOperation.cs +++ b/src/AutoRest.CSharp/Mgmt/Models/MgmtClientOperation.cs @@ -17,6 +17,7 @@ using static AutoRest.CSharp.Mgmt.Decorator.ParameterMappingBuilder; using static AutoRest.CSharp.Output.Models.MethodSignatureModifiers; using static AutoRest.CSharp.Common.Output.Models.Snippets; +using AutoRest.CSharp.Mgmt.Output.Samples; namespace AutoRest.CSharp.Mgmt.Models { @@ -31,24 +32,24 @@ internal class MgmtClientOperation : IReadOnlyList { private const int PropertyBagThreshold = 5; private readonly Parameter? _extensionParameter; - public static MgmtClientOperation? FromOperations(IReadOnlyList operations, FormattableString idVariableName, Parameter? extensionParameter = null, bool isConvenientOperation = false) + public static MgmtClientOperation? FromOperations(MgmtTypeProvider enclosingProvider, IReadOnlyList operations, FormattableString idVariableName, Parameter? extensionParameter = null, bool isConvenientOperation = false) { if (operations.Count > 0) { - return new MgmtClientOperation(operations.OrderBy(operation => operation.Name).ToArray(), idVariableName, extensionParameter, isConvenientOperation); + return new MgmtClientOperation(enclosingProvider, operations.OrderBy(operation => operation.Name).ToArray(), idVariableName, extensionParameter, isConvenientOperation); } return null; } - public static MgmtClientOperation FromOperation(MgmtRestOperation operation, FormattableString idVariableName, Parameter? extensionParameter = null, bool isConvenientOperation = false) + public static MgmtClientOperation FromOperation(MgmtTypeProvider enclosingProvider, MgmtRestOperation operation, FormattableString idVariableName, Parameter? extensionParameter = null, bool isConvenientOperation = false) { - return new MgmtClientOperation(new List { operation }, idVariableName, extensionParameter, isConvenientOperation); + return new MgmtClientOperation(enclosingProvider, new List { operation }, idVariableName, extensionParameter, isConvenientOperation); } - public static MgmtClientOperation FromClientOperation(MgmtClientOperation other, FormattableString idVariableName, Parameter? extensionParameter = null, bool isConvenientOperation = false, IReadOnlyList? parameterOverride = null) + public static MgmtClientOperation FromClientOperation(MgmtTypeProvider enclosingProvider, MgmtClientOperation other, FormattableString idVariableName, Parameter? extensionParameter = null, bool isConvenientOperation = false, IReadOnlyList? parameterOverride = null) { - return new MgmtClientOperation(other._operations, idVariableName, extensionParameter, isConvenientOperation, parameterOverride); + return new MgmtClientOperation(enclosingProvider, other._operations, idVariableName, extensionParameter, isConvenientOperation, parameterOverride); } internal FormattableString IdVariableName { get; } @@ -66,17 +67,19 @@ public static MgmtClientOperation FromClientOperation(MgmtClientOperation other, public IReadOnlyList PropertyBagUnderlyingParameters => IsPropertyBagOperation ? _passThroughParams : Array.Empty(); + private readonly MgmtTypeProvider _enclosingProvider; private readonly IReadOnlyList _operations; - private MgmtClientOperation(IReadOnlyList operations, FormattableString idVariableName, Parameter? extensionParameter, bool isConvenientOperation = false) + private MgmtClientOperation(MgmtTypeProvider enclosingProvider, IReadOnlyList operations, FormattableString idVariableName, Parameter? extensionParameter, bool isConvenientOperation = false) { + _enclosingProvider = enclosingProvider; _operations = operations; _extensionParameter = extensionParameter; IdVariableName = idVariableName; IsConvenientOperation = isConvenientOperation; } - private MgmtClientOperation(IReadOnlyList operations, FormattableString idVariableName, Parameter? extensionParameter, bool isConvenientOperation = false, IReadOnlyList? parameterOverride = null) : this(operations, idVariableName, extensionParameter, isConvenientOperation) + private MgmtClientOperation(MgmtTypeProvider enclosingProvider, IReadOnlyList operations, FormattableString idVariableName, Parameter? extensionParameter, bool isConvenientOperation = false, IReadOnlyList? parameterOverride = null) : this(enclosingProvider, operations, idVariableName, extensionParameter, isConvenientOperation) { _methodParameters = parameterOverride; } @@ -282,5 +285,30 @@ private IReadOnlyList EnsureMethodParameters() parameters.Add(KnownParameters.CancellationTokenParameter); return parameters; } + + private IReadOnlyList? _samples; + public IReadOnlyList Samples => _samples ??= EnsureSamples(); + + private IReadOnlyList EnsureSamples() + { + // if the method is not a service method which directly corresponds to a rest api call, we skip the samples on it. + // for example, those methods that manipulate the tags. + // the spec does not have such operations, therefore there is impossible to have examples for them. + if (IsConvenientOperation) + { + return []; + } + var samples = new List(); + foreach (var restOperation in this) + { + foreach (var example in restOperation.Operation.Examples) + { + var sample = new MgmtOperationSample(restOperation.OperationId, _enclosingProvider, this, restOperation.Operation, example); + samples.Add(sample); + } + } + + return samples; + } } } diff --git a/src/AutoRest.CSharp/Mgmt/Output/ArmClientExtension.cs b/src/AutoRest.CSharp/Mgmt/Output/ArmClientExtension.cs index 9b8b63d9a94..dda4548715a 100644 --- a/src/AutoRest.CSharp/Mgmt/Output/ArmClientExtension.cs +++ b/src/AutoRest.CSharp/Mgmt/Output/ArmClientExtension.cs @@ -53,7 +53,7 @@ protected override IEnumerable EnsureClientOperations() var scopeResourceTypes = requestPaths.Select(requestPath => requestPath.GetParameterizedScopeResourceTypes() ?? Enumerable.Empty()).SelectMany(types => types).Distinct(); var scopeTypes = ResourceTypeBuilder.GetScopeTypeStrings(scopeResourceTypes); var parameterOverride = clientOperation.MethodParameters.Skip(1).Prepend(GetScopeParameter(scopeTypes)).Prepend(ExtensionParameter).ToArray(); - var newOp = MgmtClientOperation.FromClientOperation(clientOperation, IdVariableName, extensionParameter: extensionParamToUse, parameterOverride: parameterOverride); + var newOp = MgmtClientOperation.FromClientOperation(this, clientOperation, IdVariableName, extensionParameter: extensionParamToUse, parameterOverride: parameterOverride); yield return newOp; } } diff --git a/src/AutoRest.CSharp/Mgmt/Output/MgmtExtension.cs b/src/AutoRest.CSharp/Mgmt/Output/MgmtExtension.cs index 1b2c18d8627..5adde4dc28b 100644 --- a/src/AutoRest.CSharp/Mgmt/Output/MgmtExtension.cs +++ b/src/AutoRest.CSharp/Mgmt/Output/MgmtExtension.cs @@ -97,6 +97,7 @@ protected override IEnumerable EnsureClientOperations() // some of the values are calculated multiple times (here and in writers). // we just leave this implementation here since it could work for now return MgmtClientOperation.FromOperation( + this, new MgmtRestOperation( operation, operation.GetRequestPath(), diff --git a/src/AutoRest.CSharp/Mgmt/Output/MgmtMockableExtension.cs b/src/AutoRest.CSharp/Mgmt/Output/MgmtMockableExtension.cs index b7a57b43334..a864e31abc0 100644 --- a/src/AutoRest.CSharp/Mgmt/Output/MgmtMockableExtension.cs +++ b/src/AutoRest.CSharp/Mgmt/Output/MgmtMockableExtension.cs @@ -65,7 +65,7 @@ protected override IEnumerable EnsureClientOperations() foreach (var (_, operations) in operationDict) { - yield return MgmtClientOperation.FromOperations(operations.SelectMany(clientOperation => clientOperation).ToList(), IdVariableName)!; + yield return MgmtClientOperation.FromOperations(this, operations.SelectMany(clientOperation => clientOperation).ToList(), IdVariableName)!; } } diff --git a/src/AutoRest.CSharp/MgmtTest/Output/MgmtTestProvider.cs b/src/AutoRest.CSharp/Mgmt/Output/MgmtTestProvider.cs similarity index 100% rename from src/AutoRest.CSharp/MgmtTest/Output/MgmtTestProvider.cs rename to src/AutoRest.CSharp/Mgmt/Output/MgmtTestProvider.cs diff --git a/src/AutoRest.CSharp/Mgmt/Output/Resource.cs b/src/AutoRest.CSharp/Mgmt/Output/Resource.cs index f04eb37771f..e077420ff6c 100644 --- a/src/AutoRest.CSharp/Mgmt/Output/Resource.cs +++ b/src/AutoRest.CSharp/Mgmt/Output/Resource.cs @@ -212,7 +212,7 @@ private static IEnumerable GetClientOperations(OperationSet oper result.Add(restOperation); } - return MgmtClientOperation.FromOperations(result, IdVariableName); + return MgmtClientOperation.FromOperations(this, result, IdVariableName); } public virtual Resource GetResource() => this; @@ -318,6 +318,7 @@ private bool DoesUpdateSchemaHaveTags(CSharpType bodyParamType) { var createOrUpdateOperation = ResourceCollection.CreateOperation.OperationMappings.Values.First(); return MgmtClientOperation.FromOperation( + this, new MgmtRestOperation( createOrUpdateOperation, "Update", @@ -358,6 +359,7 @@ protected override IEnumerable EnsureAllOperations() { var getOperation = GetOperation.OperationMappings.Values.First(); result.Add(MgmtClientOperation.FromOperation( + this, new MgmtRestOperation( getOperation, "AddTag", @@ -369,6 +371,7 @@ protected override IEnumerable EnsureAllOperations() isConvenientOperation: true)); result.Add(MgmtClientOperation.FromOperation( + this, new MgmtRestOperation( getOperation, "SetTags", @@ -379,6 +382,7 @@ protected override IEnumerable EnsureAllOperations() isConvenientOperation: true)); result.Add(MgmtClientOperation.FromOperation( + this, new MgmtRestOperation( getOperation, "RemoveTag", @@ -455,7 +459,7 @@ private IDictionary EnsureClientOperationMap() // TODO -- what if the response type is not the same? Also we need to verify they have the same parameters before we could union those together _clientOperationMap = result.Where(pair => pair.Value.Count > 0).ToDictionary( pair => pair.Key, - pair => MgmtClientOperation.FromOperations(pair.Value, IdVariableName)!); // We first filtered the ones with at least one operation, therefore this will never be null + pair => MgmtClientOperation.FromOperations(this, pair.Value, IdVariableName)!); // We first filtered the ones with at least one operation, therefore this will never be null return _clientOperationMap; } diff --git a/src/AutoRest.CSharp/Mgmt/Output/ResourceCollection.cs b/src/AutoRest.CSharp/Mgmt/Output/ResourceCollection.cs index 7716088fb6c..f29e74131cc 100644 --- a/src/AutoRest.CSharp/Mgmt/Output/ResourceCollection.cs +++ b/src/AutoRest.CSharp/Mgmt/Output/ResourceCollection.cs @@ -240,6 +240,7 @@ protected override IEnumerable EnsureAllOperations() { var getMgmtRestOperation = GetOperation.OperationMappings.Values.First(); result.Add(MgmtClientOperation.FromOperation( + this, new MgmtRestOperation( getMgmtRestOperation, "Exists", @@ -247,6 +248,7 @@ protected override IEnumerable EnsureAllOperations() $"Checks to see if the resource exists in azure."), IdVariableName)); result.Add(MgmtClientOperation.FromOperation( + this, new MgmtRestOperation( getMgmtRestOperation, "GetIfExists", diff --git a/src/AutoRest.CSharp/MgmtTest/Models/Sample.cs b/src/AutoRest.CSharp/Mgmt/Output/Samples/MgmtOperationSample.cs similarity index 86% rename from src/AutoRest.CSharp/MgmtTest/Models/Sample.cs rename to src/AutoRest.CSharp/Mgmt/Output/Samples/MgmtOperationSample.cs index 8556279d7b7..1837fbe3614 100644 --- a/src/AutoRest.CSharp/MgmtTest/Models/Sample.cs +++ b/src/AutoRest.CSharp/Mgmt/Output/Samples/MgmtOperationSample.cs @@ -4,26 +4,27 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text.RegularExpressions; using System.Threading.Tasks; using AutoRest.CSharp.Common.Input; using AutoRest.CSharp.Common.Input.Examples; +using AutoRest.CSharp.Common.Output.Expressions.ValueExpressions; using AutoRest.CSharp.Common.Utilities; -using AutoRest.CSharp.Generation.Types; using AutoRest.CSharp.Mgmt.Decorator; using AutoRest.CSharp.Mgmt.Models; -using AutoRest.CSharp.Mgmt.Output; using AutoRest.CSharp.Output.Models; using AutoRest.CSharp.Output.Models.Shared; +using AutoRest.CSharp.Output.Samples.Models; using AutoRest.CSharp.Utilities; using Azure; -using MappingObject = System.Collections.Generic.Dictionary; +using NUnit.Framework; +using static AutoRest.CSharp.Common.Output.Models.Snippets; +using MappingObject = System.Collections.Generic.Dictionary; -namespace AutoRest.CSharp.MgmtTest.Models +namespace AutoRest.CSharp.Mgmt.Output.Samples { - internal class Sample : OperationExample + internal class MgmtOperationSample : OperationExample { - public Sample(string operationId, MgmtTypeProvider carrier, MgmtClientOperation operation, InputOperation inputOperation, InputOperationExample example) : base(operationId, carrier, operation, inputOperation, example) + public MgmtOperationSample(string operationId, MgmtTypeProvider carrier, MgmtClientOperation operation, InputOperation inputOperation, InputOperationExample example) : base(operationId, carrier, operation, inputOperation, example) { _methodName = $"{Operation.Name}_{Name.ToCleanName()}"; } @@ -38,7 +39,10 @@ public Sample(string operationId, MgmtTypeProvider carrier, MgmtClientOperation Modifiers: MethodSignatureModifiers.Public | MethodSignatureModifiers.Async, ReturnType: typeof(Task), ReturnDescription: null, - Parameters: Array.Empty()); + Parameters: [], + Attributes: _attributes); + + private readonly CSharpAttribute[] _attributes = [new CSharpAttribute(typeof(TestAttribute)), new CSharpAttribute(typeof(IgnoreAttribute), Literal("Only validating compilation of examples"))]; private MgmtTypeProvider? _parent; public MgmtTypeProvider? Parent => _parent ??= GetParent(); @@ -100,9 +104,9 @@ private Tuple EnsureParameterValueMapping() { // this parameter is not from body which means its type should be primary which means "default" keyword should be able to handle // the default value (also string because we disabled nullable in generated code) - var warning = $"No value is provided for {parameter.Name} in example '{this.Name}'. Please consider adding a proper example value for it in swagger"; + var warning = $"No value is provided for {parameter.Name} in example '{Name}'. Please consider adding a proper example value for it in swagger"; AutoRestLogger.Warning(warning).Wait(); - var pv = new ExampleParameterValue(parameter, $"default /* Warning: {warning}*/"); + var pv = new ExampleParameterValue(parameter, DefaultOf(parameter.Type)); if (Operation.IsPropertyBagOperation && propertyBagParamNames.Contains(parameter.Name)) { propertyBagMapping.Add(parameter.Name, pv); @@ -134,7 +138,7 @@ private static bool ProcessKnownParameters(MappingObject result, Parameter param { if (parameter == KnownParameters.WaitForCompletion) { - result.Add(parameter.Name, new ExampleParameterValue(parameter, $"{typeof(WaitUntil)}.Completed")); + result.Add(parameter.Name, new ExampleParameterValue(parameter, new TypeReference(typeof(WaitUntil)).Property(nameof(WaitUntil.Completed)))); return true; } if (parameter == KnownParameters.CancellationTokenParameter) diff --git a/src/AutoRest.CSharp/Mgmt/Output/Samples/MgmtSampleProvider.cs b/src/AutoRest.CSharp/Mgmt/Output/Samples/MgmtSampleProvider.cs new file mode 100644 index 00000000000..aa9a587830c --- /dev/null +++ b/src/AutoRest.CSharp/Mgmt/Output/Samples/MgmtSampleProvider.cs @@ -0,0 +1,690 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using AutoRest.CSharp.Common.Input; +using AutoRest.CSharp.Common.Output.Expressions.Statements; +using AutoRest.CSharp.Common.Output.Expressions.ValueExpressions; +using AutoRest.CSharp.Common.Output.Models; +using AutoRest.CSharp.Common.Output.Models.Samples; +using AutoRest.CSharp.Generation.Types; +using AutoRest.CSharp.Input.Source; +using AutoRest.CSharp.Mgmt.Decorator; +using AutoRest.CSharp.Mgmt.Models; +using AutoRest.CSharp.Output.Models; +using AutoRest.CSharp.Output.Models.Shared; +using AutoRest.CSharp.Output.Models.Types; +using AutoRest.CSharp.Utilities; +using Azure; +using Azure.Core; +using Azure.ResourceManager; +using Azure.ResourceManager.Resources; +using static AutoRest.CSharp.Common.Output.Models.Snippets; + +namespace AutoRest.CSharp.Mgmt.Output.Samples +{ + internal class MgmtSampleProvider : ExpressionTypeProvider + { + private const string _createResourceIdentifierMethodName = "CreateResourceIdentifier"; + protected readonly MgmtTypeProvider _client; + + private readonly HashSet _skippedOperations; + + public MgmtSampleProvider(string defaultNamespace, MgmtTypeProvider client, SourceInputModel? sourceInputModel) : base($"{defaultNamespace}.Samples", sourceInputModel) + { + DeclarationModifiers = TypeSignatureModifiers.Public | TypeSignatureModifiers.Partial; + DefaultName = $"Sample_{client.Type.Name}"; + _client = client; + _skippedOperations = new HashSet(Configuration.MgmtTestConfiguration?.SkippedOperations ?? []); + } + + public bool IsEmpty => !Methods.Any(); + + protected override string DefaultName { get; } + + protected override IEnumerable BuildUsings() + { + yield return "Azure.Identity"; // we need this using because we might need to call `new DefaultAzureCredential` from `Azure.Identity` package, but Azure.Identity package is not a dependency of the generator project. + } + + private Method BuildSample(MgmtOperationSample sample, bool isAsync) + { + var signature = sample.GetMethodSignature(false); + + return new Method(signature, BuildSampleBody(sample, isAsync)); + } + + private MethodBodyStatement BuildSampleBody(MgmtOperationSample example, bool isAsync) + { + var statements = new List() + { + new SingleLineCommentStatement($"Generated from example definition: {example.ExampleFilepath}"), + new SingleLineCommentStatement($"this example is just showing the usage of \"{example.OperationId}\" operation, for the dependent resources, they will have to be created separately."), + EmptyLine, + new SingleLineCommentStatement("get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line"), + Declare(typeof(TokenCredential), "cred", new FormattableStringToExpression($"new DefaultAzureCredential()"), out var cred), // this project does not use Azure.Identity as a dependency, therefore this is the only way to write this. + new SingleLineCommentStatement("authenticate your client"), + Declare(typeof(ArmClient), "client", New.Instance(typeof(ArmClient), cred), out var client), + EmptyLine, + BuildSampleMethodInvocation(example, client, out var result), + EmptyLine, + BuildResultHandlingStatement(result) + }; + + return statements; + } + + private MethodBodyStatement BuildResultHandlingStatement(TypedValueExpression? result) + { + if (result == null) + { + return InvokeConsoleWriteLine(Literal("Succeeded")); + } + else + { + if (result.Type.IsNullable) + { + return new IfElseStatement( + Equal(result, Null), + InvokeConsoleWriteLine(Literal("Succeeded with null as result")), + BuildNotNullResultHandlingStatement(result)); + } + else + { + return BuildNotNullResultHandlingStatement(result); + } + } + } + + private static MethodBodyStatement BuildNotNullResultHandlingStatement(TypedValueExpression result) + { + if (result.Type is { IsFrameworkType: false, Implementation: Resource resource }) + { + return BuildResourceResultHandling(result, resource); + } + else if (result.Type is { IsFrameworkType: false, Implementation: ResourceData resourceData }) + { + return BuildResourceDataResultHandling(result, resourceData); + } + else + { + return BuildOtherResultHandling(result); + } + + static MethodBodyStatement BuildResourceResultHandling(TypedValueExpression result, Resource resource) + { + return new MethodBodyStatement[] + { + new SingleLineCommentStatement((FormattableString)$"the variable {result} is a resource, you could call other operations on this instance as well"), + new SingleLineCommentStatement("but just for demo, we get its data from this resource instance"), + Declare(resource.ResourceData.Type, "resourceData", result.Property("Data"), out var resourceData), + BuildResourceDataResultHandling(resourceData, resource.ResourceData) + }; + } + + static MethodBodyStatement BuildResourceDataResultHandling(TypedValueExpression result, ResourceData resourceData) + { + return new MethodBodyStatement[] + { + new SingleLineCommentStatement("for demo we just print out the id"), + InvokeConsoleWriteLine(new FormattableStringExpression("Succeeded on id: {0}", result.Property("Id"))) + }; + } + + static MethodBodyStatement BuildOtherResultHandling(TypedValueExpression result) + { + return InvokeConsoleWriteLine(new FormattableStringExpression("Succeeded: {0}", result)); + } + } + + private MethodBodyStatement BuildSampleMethodInvocation(MgmtOperationSample example, ValueExpression client, out TypedValueExpression? result) + => example.Carrier switch + { + ResourceCollection collection => BuildSampleMethodBodyForResourceCollection(example, client, collection, out result), + Resource resource => BuildSampleMethodBodyForResource(example, client, resource, out result), + MgmtExtension extension => BuildSampleMethodBodyForExtension(example, client, extension, out result), + _ => throw new InvalidOperationException("This should never happen") + }; + + private MethodBodyStatement BuildSampleMethodBodyForExtension(MgmtOperationSample example, ValueExpression client, MgmtExtension extension, out TypedValueExpression? result) + { + var resourceName = GetResourceName(extension); + return new MethodBodyStatement[] + { + // get extension resource instance + BuildGetResourceStatementFromExtension(extension, example, client, out var instance), + EmptyLine, + BuildSampleOperationStatement(example, instance, out result) + }; + } + + private MethodBodyStatement BuildSampleMethodBodyForResource(MgmtOperationSample example, ValueExpression client, Resource resource, out TypedValueExpression? result) + { + var statements = new List() + { + BuildGetResourceStatement(resource, example, client, out var instance), + EmptyLine, + BuildSampleOperationStatement(example, instance, out result), + }; + + return statements; + } + + private MethodBodyStatement BuildSampleMethodBodyForResourceCollection(MgmtOperationSample example, ValueExpression client, ResourceCollection collection, out TypedValueExpression? result) + { + return new MethodBodyStatement[] + { + BuildGetCollectionStatement(collection, example, client, out var instance), + EmptyLine, + BuildSampleOperationStatement(example, instance, out result), + }; + } + + private MethodBodyStatement BuildSampleOperationStatement(MgmtOperationSample example, ValueExpression instance, out TypedValueExpression? result) + { + if (example.IsLro) + { + return BuildSampleOperationStatementForLro(example, instance, out result); + } + else if (example.IsPageable) + { + result = null; // pageable operations do not return a result to handle + return BuildSampleOperationStatementForPageable(example, instance); + } + + return BuildSampleOperationStatementForNormal(example, instance, out result); + } + + private MethodBodyStatement BuildSampleOperationStatementForLro(MgmtOperationSample example, ValueExpression instance, out TypedValueExpression? result) + { + var statements = new List + { + new SingleLineCommentStatement("invoke the operation") + }; + + // collect all the parameters + var (parameterDeclaration, parameterArguments) = BuildOperationInvocationParameters(example); + statements.Add(parameterDeclaration); + var operationInvocationExpression = BuildOperationInvocation(instance, example.Operation, parameterArguments); + var lroType = example.Operation.ReturnType; + if (lroType.IsGenericType) + { + statements.Add( + Declare(lroType, "lro", operationInvocationExpression, out var lro) + ); + var resultVar = new VariableReference(lroType.Arguments[0], "result"); + statements.Add( + Declare(resultVar, lro.Property("Value")) + ); + result = resultVar; + } + else + { + statements.Add(new InvokeInstanceMethodStatement(operationInvocationExpression)); + result = null; + } + return statements; + } + + private MethodBodyStatement BuildSampleOperationStatementForPageable(MgmtOperationSample example, ValueExpression instance) + { + var statements = new List + { + new SingleLineCommentStatement("invoke the operation and iterate over the result") + }; + + // collect the parameters + var (parameterDeclaration, parameterArguments) = BuildOperationInvocationParameters(example); + statements.Add(parameterDeclaration); + var operationInvocationExpression = BuildOperationInvocation(instance, example.Operation, parameterArguments); + statements.Add( + new ForeachStatement(example.Operation.ReturnType, "item", operationInvocationExpression, true, out var item) + { + BuildResultHandlingStatement(item) + } + ); + + return statements; + } + + private MethodBodyStatement BuildSampleOperationStatementForNormal(MgmtOperationSample example, ValueExpression instance, out TypedValueExpression? result) + { + var statements = new List + { + new SingleLineCommentStatement("invoke the operation") + }; + + // collect all the parameters + var (parameterDeclaration, parameterArguments) = BuildOperationInvocationParameters(example); + statements.Add(parameterDeclaration); + var operationInvocationExpression = BuildOperationInvocation(instance, example.Operation, parameterArguments); + var returnType = example.Operation.ReturnType; + if (returnType.IsGenericType) + { + // if the type is NullableResponse, there is no implicit convert, so we have to explicitly unwrap it + if (returnType.IsFrameworkType && returnType.FrameworkType == typeof(NullableResponse<>)) + { + var unwrappedReturnType = returnType.Arguments[0].WithNullable(true); + statements.Add( + Declare(returnType, Configuration.ApiTypes.ResponseParameterName, operationInvocationExpression, out var valueResponse) + ); + var resultVar = new VariableReference(unwrappedReturnType, "result"); + statements.Add( + Declare(resultVar, new TernaryConditionalOperator(valueResponse.Property(nameof(NullableResponse.HasValue)), valueResponse.Property(nameof(NullableResponse.Value)), Null)) + ); + result = resultVar; + } + else + { + // an operation with a response + var unwrappedReturnType = returnType.Arguments[0]; + // if the type inside Response is a generic type, somehow the implicit convert Response => T does not work, we have to explicitly unwrap it + if (unwrappedReturnType.IsGenericType) + { + statements.Add( + Declare(returnType, Configuration.ApiTypes.ResponseParameterName, operationInvocationExpression, out var valueResponse) + ); + // unwrap the response + var resultVar = new VariableReference(unwrappedReturnType, "result"); + statements.Add( + Declare(resultVar, valueResponse.Property(nameof(Response.Value))) + ); + result = resultVar; + } + else // if it is a type provider type, we could rely on the implicit convert Response => T + { + var resultVar = new VariableReference(unwrappedReturnType, "result"); + statements.Add( + Declare(resultVar, operationInvocationExpression) + ); + result = resultVar; + } + } + } + else + { + // an operation without a response + statements.Add( + new InvokeInstanceMethodStatement(operationInvocationExpression) + ); + result = null; + } + + return statements; + } + + private (MethodBodyStatement ParameterDeclarations, IReadOnlyList Arguments) BuildOperationInvocationParameters(MgmtOperationSample example) + { + var statements = new List(); + var methodParameters = example.Operation.MethodParameters; + var arguments = new List(methodParameters.Count); + foreach (var parameter in methodParameters) + { + if (example.ParameterValueMapping.TryGetValue(parameter.Name, out var parameterValue)) + { + // if we could get an example value out of the map, we just use it. + var expression = ExampleValueSnippets.GetExpression(parameterValue, parameter.SerializationFormat); + + // some parameters are always inline + if (_inlineParameters.Contains(parameter)) + { + arguments.Add(expression); + } + else + { + statements.Add(Declare(parameter.Type, parameter.Name, expression, out var p)); + if (parameter.IsOptionalInSignature) + { + arguments.Add(new PositionalParameterReference(parameter.Name, p)); + } + else + { + arguments.Add(p); + } + } + } + else if (parameter.IsPropertyBag) + { + // get the model for the bag + var bag = parameter.Type.Implementation as ModelTypeProvider; + // property bag should always be a ModelTypeProvider, but just in case + if (bag == null) + { + arguments.Add(Null); + continue; + } + // build property bag assignment + var ctor = bag.InitializationConstructor; + var visitedProperties = new HashSet(); + var ctorArguments = new List(); + Dictionary? initializationProperties = null; + foreach (var p in ctor.Signature.Parameters) + { + var prop = ctor.FindPropertyInitializedByParameter(p); + if (prop != null) + { + visitedProperties.Add(prop); + } + if (example.PropertyBagParamValueMapping.TryGetValue(p.Name, out var value)) + { + statements.Add(Declare(p.Type, p.Name, ExampleValueSnippets.GetExpression(value, p.SerializationFormat), out var pVar)); + ctorArguments.Add(pVar); + } + else + { + ctorArguments.Add(Default.CastTo(p.Type)); + } + } + // get the optional properties + foreach (var prop in bag.Properties) + { + if (visitedProperties.Contains(prop)) + { + continue; + } + if (example.PropertyBagParamValueMapping.TryGetValue(prop.Declaration.Name.ToVariableName(), out var value)) + { + initializationProperties ??= new Dictionary(); + initializationProperties.Add(prop.Declaration.Name, ExampleValueSnippets.GetExpression(value, prop.SerializationFormat)); + } + } + statements.Add(Declare(parameter.Type, parameter.Name, New.Instance(ctor.Signature, ctorArguments, initializationProperties), out var options)); + arguments.Add(options); + } + } + + return (statements, arguments); + } + + private InvokeInstanceMethodExpression BuildOperationInvocation(ValueExpression instance, MgmtClientOperation operation, IReadOnlyList parameterArguments, bool isAsync = true) + { + return new InvokeInstanceMethodExpression(instance, GetMethodName(operation.Name, isAsync), parameterArguments, TypeArguments: null, CallAsAsync: isAsync && !operation.IsPagingOperation, AddConfigureAwaitFalse: false); + } + + private MethodBodyStatement BuildGetCollectionWithoutParent(ValueExpression client, ResourceCollection collection, out TypedValueExpression instance) + { + // Can't use CSharpType.Equals(typeof(...)) because the CSharpType.Equals(Type) would assume itself is a FrameworkType, but here it's generated when IsArmCore=true + if (Configuration.MgmtConfiguration.IsArmCore && collection.Type.Name == nameof(TenantCollection)) + { + return Declare(collection.Type, "collection", client.Invoke("GetTenants"), out instance); + } + else + { + // TODO: add support when we found any other case + throw new NotSupportedException("Unsupported type to get collection without parent: " + collection.Type.Name); + } + } + + private MethodBodyStatement BuildGetCollectionStatement(ResourceCollection collection, MgmtOperationSample example, ValueExpression client, out TypedValueExpression instance) + { + var parent = example.Parent; + + if (parent == null) + { + return BuildGetCollectionWithoutParent(client, collection, out instance); + } + + var parentName = GetResourceName(parent); + var statements = new List(); + + var resourceName = collection.Resource.ResourceName; + statements.Add( + BuildGetResourceStatement(parent, example, client, out var parentVar) + ); + + // write get collection + statements.Add(EmptyLine); + statements.Add( + new SingleLineCommentStatement($"get the collection of this {collection.Resource.Type.Name}") + ); + var getResourceCollectionMethodName = $"Get{resourceName.ResourceNameToPlural()}"; + var arguments = new List(); + + // if the extension is on ArmResource, we need an extra "scope" parameter before its actual parameters + if (parent is MgmtExtension extension && extension.ArmCoreType == typeof(ArmResource)) + { + statements.Add( + BuildCreateScopeResourceIdentifier(example, example.RequestPath.GetScopePath(), out var scopeId) + ); + arguments.Add(New.Instance(typeof(ResourceIdentifier), scopeId)); + } + + foreach (var extraParameter in collection.ExtraConstructorParameters) + { + if (example.ParameterValueMapping.TryGetValue(extraParameter.Name, out var exampleParameterValue)) + { + statements.Add( + Declare(extraParameter.Type, extraParameter.Name, ExampleValueSnippets.GetExpression(exampleParameterValue, extraParameter.SerializationFormat), out var arg) + ); + arguments.Add(arg); + } + } + + // call the method to get the collection instance + statements.Add( + Declare(collection.Type, "collection", parentVar.Invoke(getResourceCollectionMethodName, arguments), out instance) + ); + + return statements; + } + + private MethodBodyStatement BuildGetResourceStatement(MgmtTypeProvider carrierResource, OperationExample example, ValueExpression client, out TypedValueExpression instance) + => carrierResource switch + { + ResourceCollection => throw new InvalidOperationException($"ResourceCollection is not supported here"), + Resource parentResource => BuildGetResourceStatementFromResource(parentResource, example, client, out instance), + MgmtExtension parentExtension => BuildGetResourceStatementFromExtension(parentExtension, example, client, out instance), + _ => throw new InvalidOperationException($"Unknown parent {carrierResource.GetType()}"), + }; + + private MethodBodyStatement BuildGetResourceStatementFromResource(Resource resource, OperationExample example, ValueExpression client, out TypedValueExpression resourceVar) + { + // Can't use CSharpType.Equals(typeof(...)) because the CSharpType.Equals(Type) would assume itself is a FrameworkType, but here it's generated when IsArmCore=true + if (Configuration.MgmtConfiguration.IsArmCore && resource.Type.Name == nameof(TenantResource)) + { + return BuildGetResourceStatementFromTenantResource(resource, example, client, out resourceVar); + } + else + { + var resourceName = GetResourceName(resource); + return new MethodBodyStatement[] + { + new SingleLineCommentStatement($"this example assumes you already have this {resourceName} created on azure"), + new SingleLineCommentStatement($"for more information of creating {resourceName}, please refer to the document of {resourceName}"), + BuildCreateResourceIdentifier(resource.RequestPath, resource.Type, example, out var id), + Declare(resource.Type, resource.ResourceName.ToVariableName(), client.Invoke($"Get{resourceName}", id), out resourceVar) + }; + } + } + + private MethodBodyStatement BuildGetResourceStatementFromExtension(MgmtExtension extension, OperationExample example, ValueExpression client, out TypedValueExpression resourceVar) + { + if (extension.ArmCoreType == typeof(TenantResource)) + { + return BuildGetResourceStatementFromTenantResource(extension, example, client, out resourceVar); + } + else if (extension.ArmCoreType == typeof(ArmResource) || extension.ArmCoreType == typeof(ArmClient)) + { + return BuildGetResourceStatementFromArmResourceOrArmClient(example, client, out resourceVar); + } + else + { + return BuildGetResourceStatementForOther(extension, example, client, out resourceVar); + } + } + + private MethodBodyStatement BuildGetResourceStatementFromTenantResource(MgmtTypeProvider resource, OperationExample example, ValueExpression client, out TypedValueExpression resourceVar) + { + return Declare(typeof(TenantResource), resource.ResourceName.ToVariableName(), client.Invoke("GetTenants").Invoke("GetAllAsync").Invoke("GetAsyncEnumerator").Property("Current"), out resourceVar); + } + + private MethodBodyStatement BuildGetResourceStatementFromArmResourceOrArmClient(OperationExample example, ValueExpression client, out TypedValueExpression resourceVar) + { + if (client is TypedValueExpression typedClient) + { + resourceVar = typedClient; + } + else + { + resourceVar = new TypedValueExpression(typeof(ArmClient), client); + } + return EmptyStatement; + } + + private MethodBodyStatement BuildGetResourceStatementForOther(MgmtExtension extension, OperationExample example, ValueExpression client, out TypedValueExpression resourceVar) + { + var resourceName = GetResourceName(extension); + return new MethodBodyStatement[] + { + new SingleLineCommentStatement($"this example assumes you already have this {resourceName} created on azure"), + new SingleLineCommentStatement($"for more information of creating {resourceName}, please refer to the document of {resourceName}"), + BuildCreateResourceIdentifier(extension.ContextualPath, extension.ArmCoreType, example, out var id), + Declare(extension.ArmCoreType, extension.ResourceName.ToVariableName(), client.Invoke($"Get{resourceName}", id), out resourceVar) + }; + } + + private string GetResourceName(MgmtTypeProvider provider) => provider switch + { + Resource resource => resource.Type.Name, + MgmtExtension extension => extension.ArmCoreType.Name, + _ => throw new InvalidOperationException("Should never happen") + }; + + private MethodBodyStatement BuildCreateResourceIdentifier(RequestPath resourcePath, CSharpType typeOfResource, OperationExample example, out TypedValueExpression id) + { + var scopePath = resourcePath.GetScopePath(); + if (scopePath.IsRawParameterizedScope()) + { + return BuildCreateResourceIdentifierForScopePath(example, resourcePath, typeOfResource, out id); + } + else + { + return BuildCreateResourceIdentifierForUsualPath(example, resourcePath, typeOfResource, out id); + } + } + + private MethodBodyStatement BuildCreateResourceIdentifierForUsualPath(OperationExample example, RequestPath resourcePath, CSharpType typeOfResource, out TypedValueExpression id) + { + var statements = new List(); + // try to figure out ref segments from requestPath according the ones from resource Path + // Dont match the path side-by-side because + // 1. there is a case that the parameter names are different + // 2. the path structure may be different totally when customized, + // i.e. in ResourceManager, parent of /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} + // is configured to /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} + var myRefs = example.RequestPath.Where(s => s.IsReference); + var resourceRefCount = resourcePath.Where(s => s.IsReference).Count(); + var references = new List(resourceRefCount); + foreach (var reference in myRefs.Take(resourceRefCount)) + { + var exampleValue = example.FindInputExampleValueFromReference(reference.Reference); + var referenceStatement = Declare(reference.Type, reference.ReferenceName, ExampleValueSnippets.GetExpression(reference.Type, exampleValue), out var referenceVar); + statements.Add(referenceStatement); + references.Add(referenceVar); + } + + var idStatement = Declare(typeof(ResourceIdentifier), $"{typeOfResource.Name}Id".ToVariableName(), new InvokeStaticMethodExpression(typeOfResource, _createResourceIdentifierMethodName, references), out id); + statements.Add(idStatement); + + return statements; + } + + private MethodBodyStatement BuildCreateScopeResourceIdentifier(OperationExample example, RequestPath operationScopePath, out TypedValueExpression scopeId) + { + var statements = new List(); + var scopeValues = new List(); + foreach (var reference in operationScopePath.Where(segment => segment.IsReference)) + { + var exampleValue = example.FindInputExampleValueFromReference(reference.Reference); + var scopeRefStatement = Declare(reference.Type, reference.ReferenceName, ExampleValueSnippets.GetExpression(reference.Type, exampleValue), out var scopeRefVar); + statements.Add(scopeRefStatement); + scopeValues.Add(scopeRefVar); + } + + if (operationScopePath.Count == 1) + { + // the scope in the id is an explicit scope, such as a request path defined like: `/{scope}/providers/Microsoft.Something/roleDefinitions/{name}` therefore we do not have do anything special for it + //idArguments.AddRange(scopeValues); + scopeId = scopeValues[0]; + } + else + { + // this scope is an implicit scope, such as a request path defined like: `/subscriptions/{subsId}/providers/Microsoft.Something/roleDefinitions/{name}` but we changed this in our generator to make it a scope resource + var scopeDeclarationStatement = Declare(typeof(string), "scope", new FormattableStringExpression(operationScopePath, scopeValues), out var scope); + statements.Add(scopeDeclarationStatement); + scopeId = scope; + } + + return statements; + } + + private MethodBodyStatement BuildCreateResourceIdentifierForScopePath(OperationExample example, RequestPath resourcePath, CSharpType typeOfResource, out TypedValueExpression id) + { + var statements = new List(); + var operationScopePath = example.RequestPath.GetScopePath(); + var resourceScopePath = resourcePath.GetScopePath(); + var trimmedPath = resourcePath.TrimScope(); + var operationTrimeedPath = example.RequestPath.TrimScope(); + + var scopeValues = new List(); + foreach (var reference in operationScopePath.Where(segment => segment.IsReference)) + { + var exampleValue = example.FindInputExampleValueFromReference(reference.Reference); + var scopeRefStatement = Declare(reference.Type, reference.ReferenceName, ExampleValueSnippets.GetExpression(reference.Type, exampleValue), out var scopeRefVar); + statements.Add(scopeRefStatement); + scopeValues.Add(scopeRefVar); + } + + var idArguments = new List(); + if (operationScopePath.Count == 1) + { + // the scope in the id is an explicit scope, such as a request path defined like: `/{scope}/providers/Microsoft.Something/roleDefinitions/{name}` therefore we do not have do anything special for it + idArguments.AddRange(scopeValues); + } + else + { + // this scope is an implicit scope, such as a request path defined like: `/subscriptions/{subsId}/providers/Microsoft.Something/roleDefinitions/{name}` but we changed this in our generator to make it a scope resource + var scopeDeclarationStatement = Declare(typeof(string), "scope", new FormattableStringExpression(operationScopePath, scopeValues), out var scope); + statements.Add(scopeDeclarationStatement); + idArguments.Add(scope); + } + + foreach (var reference in operationTrimeedPath.Take(trimmedPath.Count).Where(segment => segment.IsReference)) + { + var exampleValue = example.FindInputExampleValueFromReference(reference.Reference); + var refStatement = Declare(reference.Type, reference.ReferenceName, ExampleValueSnippets.GetExpression(reference.Type, exampleValue), out var idPartVar); + statements.Add(refStatement); + idArguments.Add(idPartVar); + } + + var idStatement = Declare(typeof(ResourceIdentifier), $"{typeOfResource.Name}Id".ToVariableName(), new InvokeStaticMethodExpression(typeOfResource, _createResourceIdentifierMethodName, idArguments), out id); + statements.Add(idStatement); + + return statements; + } + + protected override IEnumerable BuildMethods() + { + foreach (var operation in _client.AllOperations) + { + if (operation.Any(o => _skippedOperations.Contains(o.OperationId))) + { + continue; + } + foreach (var sample in operation.Samples) + { + yield return BuildSample(sample, true); + } + } + } + + private static readonly HashSet _inlineParameters = [KnownParameters.WaitForCompletion, KnownParameters.CancellationTokenParameter]; + + private string GetMethodName(string methodName, bool isAsync = true) + { + return isAsync ? $"{methodName}Async" : methodName; + } + } +} diff --git a/src/AutoRest.CSharp/Mgmt/Output/Samples/OperationExample.cs b/src/AutoRest.CSharp/Mgmt/Output/Samples/OperationExample.cs new file mode 100644 index 00000000000..8bbeb8f574a --- /dev/null +++ b/src/AutoRest.CSharp/Mgmt/Output/Samples/OperationExample.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Linq; +using AutoRest.CSharp.Common.Input; +using AutoRest.CSharp.Common.Input.Examples; +using AutoRest.CSharp.Mgmt.Models; +using AutoRest.CSharp.Output.Models.Requests; + +namespace AutoRest.CSharp.Mgmt.Output.Samples +{ + internal class OperationExample + { + private readonly Lazy> _parameterNameToSerializedNameMapping; + + internal protected InputOperationExample _example; + internal protected InputOperation _inputOperation; + public string OperationId { get; } + public string Name => _example.Name!; + + public MgmtTypeProvider Carrier { get; } + + public MgmtClientOperation Operation { get; } + + private MgmtRestOperation? _restOperation; + public MgmtRestOperation RestOperation => _restOperation ??= GetRestOperationFromOperationId(); + public RequestPath RequestPath => RestOperation.RequestPath; + + /// + /// All the parameters defined in this test case + /// We do not need to distiguish between ClientParameters and MethodParameters because we usually change that in code model transformation + /// + public IEnumerable AllParameters => _example.Parameters; + private IEnumerable? _pathParameters; + public IEnumerable PathParameters => _pathParameters ??= AllParameters.Where(p => p.Parameter.Location == RequestLocation.Path); + + protected OperationExample(string operationId, MgmtTypeProvider carrier, MgmtClientOperation operation, InputOperation inputOperation, InputOperationExample example) + { + OperationId = operationId; + _example = example; + _inputOperation = inputOperation; + Carrier = carrier; + Operation = operation; + _parameterNameToSerializedNameMapping = new Lazy>(EnsureParameterSerializedNames); + } + + private MgmtRestOperation GetRestOperationFromOperationId() + { + foreach (var operation in Operation) + { + if (operation.OperationId == OperationId) + return operation; + } + + throw new InvalidOperationException($"Cannot find operationId {OperationId} in example {_inputOperation.Name}"); + } + + public InputExampleValue? FindInputExampleValueFromReference(Reference reference) + { + // find a path parameter in our path parameters for one with same name + var serializedName = GetParameterSerializedName(reference.Name); + var parameter = FindExampleParameterBySerializedName(PathParameters, serializedName); + return parameter?.ExampleValue; + } + + private Dictionary EnsureParameterSerializedNames() + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + + foreach (var requestParameter in _inputOperation.Parameters) + { + result.Add(requestParameter.Name, requestParameter.NameInRequest ?? requestParameter.Name); + } + + return result; + } + + // there are possibilities that we cannot find the corresponding parameter's serialized name. We have to return an empty here to ensure everything is going fine + protected string GetParameterSerializedName(string name) => _parameterNameToSerializedNameMapping.Value.TryGetValue(name, out var serializedName) ? serializedName : string.Empty; + + protected InputParameterExample? FindExampleParameterBySerializedName(IEnumerable parameters, string name) + => parameters.FirstOrDefault(p => p.Parameter.NameInRequest == name); + } +} diff --git a/src/AutoRest.CSharp/MgmtTest/AutoRest/MgmtTestOutputLibrary.cs b/src/AutoRest.CSharp/MgmtTest/AutoRest/MgmtTestOutputLibrary.cs deleted file mode 100644 index f07f79a2d0b..00000000000 --- a/src/AutoRest.CSharp/MgmtTest/AutoRest/MgmtTestOutputLibrary.cs +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using AutoRest.CSharp.Common.Input; -using AutoRest.CSharp.Mgmt.AutoRest; -using AutoRest.CSharp.Mgmt.Output; -using AutoRest.CSharp.MgmtTest.Models; -using AutoRest.CSharp.MgmtTest.Output.Samples; -using AutoRest.CSharp.Utilities; - -namespace AutoRest.CSharp.MgmtTest.AutoRest -{ - internal class MgmtTestOutputLibrary - { - private readonly InputNamespace _input; - private readonly HashSet _skippedOperations; - - public MgmtTestOutputLibrary(InputNamespace inputNamespace) - { - _input = inputNamespace; - _skippedOperations = new HashSet(Configuration.MgmtTestConfiguration?.SkippedOperations ?? []); - } - - private IEnumerable? _samples; - public IEnumerable Samples => _samples ??= EnsureSamples(); - - private IEnumerable EnsureSamples() - { - var result = new Dictionary>(); - foreach (var client in _input.Clients) - { - foreach (var inputOperation in client.Operations) - { - foreach (var example in inputOperation.Examples) - { - // we need to find which resource or resource collection this test case belongs - var operationId = inputOperation.OperationId!; - - // skip this operation if we find it in the `skipped-operations` configuration - if (_skippedOperations.Contains(operationId)) - continue; - - var providerAndOperations = FindCarriersFromOperationId(operationId); - foreach (var providerForExample in providerAndOperations) - { - // the operations on ArmClientExtensions are the same as the tenant extension, therefore we skip it here - // the source code generator will never write them if it is not in arm core - if (providerForExample.Carrier is ArmClientExtension) - continue; - var sample = new Sample(operationId, providerForExample.Carrier, providerForExample.Operation, inputOperation, example); - result.AddInList(sample.Owner, sample); - } - } - } - } - - foreach ((var owner, var cases) in result) - { - yield return new MgmtSampleProvider(owner, cases); - } - } - - private IEnumerable FindCarriersFromOperationId(string operationId) - { - // it is possible that an operationId does not exist in the MgmtOutputLibrary, because some of the operations are removed by design. For instance, `Operations_List`. - if (EnsureOperationIdToProviders().TryGetValue(operationId, out var result)) - return result; - return Array.Empty(); - } - - private Dictionary>? _operationNameToProviders; - private Dictionary> EnsureOperationIdToProviders() - { - if (_operationNameToProviders != null) - return _operationNameToProviders; - - _operationNameToProviders = new Dictionary>(); - // iterate all the resources and resource collection - var mgmtProviders = MgmtContext.Library.ArmResources.Cast() - .Concat(MgmtContext.Library.ResourceCollections) - .Concat(MgmtContext.Library.ExtensionWrapper.Extensions); - foreach (var provider in mgmtProviders) - { - foreach (var clientOperation in provider.AllOperations) - { - // we skip the convenient methods, AddTag, SetTags, DeleteTags, etc, because they do not have a corresponding source of test data - if (clientOperation.IsConvenientOperation) - continue; - foreach (var restOperation in clientOperation) - { - _operationNameToProviders.AddInList(restOperation.OperationId, new MgmtTypeProviderAndOperation(provider, clientOperation)); - } - } - } - - return _operationNameToProviders; - } - } -} diff --git a/src/AutoRest.CSharp/MgmtTest/AutoRest/MgmtTestTarget.cs b/src/AutoRest.CSharp/MgmtTest/AutoRest/MgmtTestTarget.cs deleted file mode 100644 index 5ce74a1760e..00000000000 --- a/src/AutoRest.CSharp/MgmtTest/AutoRest/MgmtTestTarget.cs +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Threading.Tasks; -using AutoRest.CSharp.Common.Input; -using AutoRest.CSharp.Input.Source; -using AutoRest.CSharp.Mgmt.AutoRest; -using AutoRest.CSharp.MgmtTest.AutoRest; -using AutoRest.CSharp.MgmtTest.Generation.Samples; -using AutoRest.CSharp.Output.Models.Types; - -namespace AutoRest.CSharp.AutoRest.Plugins -{ - internal class MgmtTestTarget - { - private const string SOURCE_DEFAULT_FOLDER_NAME = "src"; - private const string SOURCE_DEFAULT_OUTPUT_PATH = $"/{SOURCE_DEFAULT_FOLDER_NAME}/Generated"; - private const string MOCK_TEST_DEFAULT_OUTPUT_PATH = "/tests/Generated"; - private const string SAMPLE_DEFAULT_OUTPUT_PATH = "/samples/Generated"; - - public static async Task ExecuteAsync(GeneratedCodeWorkspace project, InputNamespace inputNamespace, SourceInputModel? sourceInputModel) - { - Debug.Assert(inputNamespace.Clients is not null); - MgmtTestOutputLibrary library; - if (sourceInputModel == null) - { - var sourceFolder = GetSourceFolder(); - var sourceCodeProject = new SourceCodeProject(sourceFolder, Configuration.SharedSourceFolders); - sourceInputModel = new SourceInputModel(await sourceCodeProject.GetCompilationAsync()); - InitializeMgmtContext(inputNamespace, sourceInputModel); - library = new MgmtTestOutputLibrary(inputNamespace); - project.AddDirectory(sourceFolder); - } - else - { - library = new MgmtTestOutputLibrary(inputNamespace); - } - - if (Configuration.MgmtTestConfiguration?.Sample ?? Configuration.GenerateSampleProject) - { - WriteSamples(project, library); - } - - if (_overriddenProjectFilenames.TryGetValue(project, out var overriddenFilenames)) - throw new InvalidOperationException($"At least one file was overridden during the generation process. Filenames are: {string.Join(", ", overriddenFilenames)}"); - - if (Configuration.MgmtTestConfiguration?.ClearOutputFolder ?? false) - { - ClearOutputFolder(); - } - } - - private static void InitializeMgmtContext(InputNamespace inputNamespace, SourceInputModel sourceInputModel) - { - MgmtContext.Initialize(new BuildContext(inputNamespace, sourceInputModel)); - - // force trigger the model initialization - foreach (var _ in MgmtContext.Library.ResourceSchemaMap.Value) - { - } - } - - private static void WriteSamples(GeneratedCodeWorkspace project, MgmtTestOutputLibrary library) - { - string outputFolder = GetOutputFolder(SAMPLE_DEFAULT_OUTPUT_PATH); - - var names = new Dictionary(); - foreach (var sample in library.Samples) - { - var sampleWriter = new MgmtSampleWriter(sample); - sampleWriter.Write(); - - var filename = GetFilename(sample.Type.Name, names); - AddGeneratedFile(project, Path.Combine(outputFolder, $"Samples/{filename}.cs"), sampleWriter.ToString()); - } - } - - private static string GetFilename(string name, Dictionary names) - { - if (names.TryGetValue(name, out var count)) - { - names[name]++; - return $"{name}{count}"; - } - - names[name] = 1; - return name; - } - - private static void ClearOutputFolder() - { - if (Configuration.MgmtTestConfiguration == null || - string.IsNullOrEmpty(Configuration.MgmtTestConfiguration.OutputFolder)) - return; - DirectoryInfo di = new DirectoryInfo(Configuration.MgmtTestConfiguration.OutputFolder); - ClearFolder(di); - } - - private static void ClearFolder(DirectoryInfo di) - { - if (di.Exists) - { - foreach (FileInfo fi in di.EnumerateFiles()) - { - try - { - fi.Delete(); - } - // Ignore the error from clearing folder - catch { } - } - foreach (DirectoryInfo subFolder in di.EnumerateDirectories()) - { - ClearFolder(subFolder); - try - { - subFolder.Delete(); - } - // Ignore the error from clearing folder - catch { } - } - } - } - - private static string GetOutputFolder(string defaultOutputPath) - { - if (!string.IsNullOrEmpty(Configuration.MgmtTestConfiguration?.OutputFolder)) - return Configuration.MgmtTestConfiguration.OutputFolder; - - string folder = FormatPath(Configuration.OutputFolder); - // if the output folder is not given explicitly, try to figure it out from general output folder if possible according to default folder structure: - // Azure.ResourceManager.XXX \ src \ Generated <- default sdk source output folder - // \ samples(or tests) \ Generated <- default sample output folder defined in msbuild - if (folder.EndsWith(SOURCE_DEFAULT_OUTPUT_PATH, StringComparison.InvariantCultureIgnoreCase)) - return FormatPath(Path.Combine(folder, $"../../{defaultOutputPath}")); - else if (folder.EndsWith(SAMPLE_DEFAULT_OUTPUT_PATH, StringComparison.InvariantCultureIgnoreCase) || folder.EndsWith(MOCK_TEST_DEFAULT_OUTPUT_PATH, StringComparison.InvariantCultureIgnoreCase)) - return folder; - else - throw new InvalidOperationException("'sample-gen.output-folder' is not configured and can't figure it out from give general output-folder"); - } - - private static string GetSourceFolder() - { - if (!string.IsNullOrEmpty(Configuration.MgmtTestConfiguration?.SourceCodePath)) - return Configuration.MgmtTestConfiguration.SourceCodePath; - - string folder = FormatPath(Configuration.OutputFolder); - string testFolder = FormatPath(Configuration.MgmtTestConfiguration?.OutputFolder); - - if (!string.IsNullOrEmpty(Configuration.MgmtTestConfiguration?.OutputFolder) && - !string.Equals(folder, testFolder, StringComparison.InvariantCultureIgnoreCase)) - { - // if the general output folder and our output folder is different, the general output folder should point to the sdk code folder src\Generated - return FormatPath(Path.Combine(Configuration.OutputFolder, "..")); - } - - // if only the general output folder is given or it's the same as our output folder. Let's try to figure it out from given output folder if possible according to default folder structure: - // Azure.ResourceManager.XXX \ src <- default sdk source folder - // \ samples(or tests) \ Generated <- default sample output folder defined in msbuild - if (folder.EndsWith(SOURCE_DEFAULT_OUTPUT_PATH, StringComparison.InvariantCultureIgnoreCase)) - return FormatPath(Path.Combine(folder, "..")); - else if (folder.EndsWith(SAMPLE_DEFAULT_OUTPUT_PATH, StringComparison.InvariantCultureIgnoreCase) || folder.EndsWith(MOCK_TEST_DEFAULT_OUTPUT_PATH, StringComparison.InvariantCultureIgnoreCase)) - return FormatPath(Path.Combine(folder, "../..", SOURCE_DEFAULT_FOLDER_NAME)); - else - throw new InvalidOperationException("'sample-gen.source-path' is not configured and can't figure it out from give output-folder and sample-gen.output-folder"); - } - - private static string FormatPath(string? path) - { - if (string.IsNullOrEmpty(path)) - return path ?? ""; - return Path.GetFullPath(path.TrimEnd('/', '\\')).Replace("\\", "/"); - } - - private static IDictionary> _addedProjectFilenames = new Dictionary>(); - private static IDictionary> _overriddenProjectFilenames = new Dictionary>(); - - private static void AddGeneratedFile(GeneratedCodeWorkspace project, string filename, string text) - { - if (!_addedProjectFilenames.TryGetValue(project, out var addedFileNames)) - { - addedFileNames = new HashSet(); - _addedProjectFilenames.Add(project, addedFileNames); - } - if (addedFileNames.Contains(filename)) - { - if (!_overriddenProjectFilenames.TryGetValue(project, out var overriddenFileNames)) - { - overriddenFileNames = new List(); - _overriddenProjectFilenames.Add(project, overriddenFileNames); - } - overriddenFileNames.Add(filename); - } - else - { - addedFileNames.Add(filename); - } - project.AddGeneratedFile(filename, text); - } - } -} diff --git a/src/AutoRest.CSharp/MgmtTest/AutoRest/SourceCodeProject.cs b/src/AutoRest.CSharp/MgmtTest/AutoRest/SourceCodeProject.cs deleted file mode 100644 index 9ab3e9e20fe..00000000000 --- a/src/AutoRest.CSharp/MgmtTest/AutoRest/SourceCodeProject.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using AutoRest.CSharp.AutoRest.Plugins; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; - -namespace AutoRest.CSharp.MgmtTest.AutoRest -{ - internal class SourceCodeProject - { - private static readonly string[] SharedFolders = { GeneratedCodeWorkspace.SharedFolder }; - private Project _sourceCodeProject; - public SourceCodeProject(string sourceCodePath, string[] sharedSourceFolders) - { - if (Uri.IsWellFormedUriString(sourceCodePath, UriKind.RelativeOrAbsolute)) - { - Uri uri = new Uri(sourceCodePath); - sourceCodePath = uri.LocalPath; - } - else - { - sourceCodePath = Path.GetFullPath(sourceCodePath); - } - - _sourceCodeProject = CreateSourceCodeProject(sourceCodePath, sharedSourceFolders); - } - - public async Task GetCompilationAsync() - { - var compilation = await _sourceCodeProject.GetCompilationAsync() as CSharpCompilation; - Debug.Assert(compilation != null); - return compilation; - } - - private static Project CreateSourceCodeProject(string sourceCodePath, string[] sharedSourceFolders) - { - var sourceCodeProject = CreateGeneratedCodeProject(); - DirectoryInfo di = new DirectoryInfo(sourceCodePath); - var genFolders = di.EnumerateDirectories(GeneratedCodeWorkspace.GeneratedFolder, SearchOption.AllDirectories).ToList(); - - sourceCodeProject = GeneratedCodeWorkspace.AddDirectory(sourceCodeProject, sourceCodePath, - // Skip adding the generated sdk code to the project - skipPredicate: sourceFile => genFolders.Exists(f => sourceFile.StartsWith(f.FullName))); - - foreach (var sharedSourceFolder in sharedSourceFolders) - { - sourceCodeProject = GeneratedCodeWorkspace.AddDirectory(sourceCodeProject, sharedSourceFolder, folders: SharedFolders); - } - - sourceCodeProject = sourceCodeProject.WithParseOptions(new CSharpParseOptions(preprocessorSymbols: new[] { "EXPERIMENTAL" })); - - return sourceCodeProject; - } - - private static Project CreateGeneratedCodeProject() - { - var workspace = new AdhocWorkspace(); - Project generatedCodeProject = workspace.AddProject("SourceCode", LanguageNames.CSharp); - - var corlibLocation = typeof(object).Assembly.Location; - var references = new List(); - - references.Add(MetadataReference.CreateFromFile(corlibLocation)); - - var trustedAssemblies = ((string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") ?? "").Split(Path.PathSeparator); - foreach (var tpl in trustedAssemblies) - { - references.Add(MetadataReference.CreateFromFile(tpl)); - } - - generatedCodeProject = generatedCodeProject - .AddMetadataReferences(references) - .WithCompilationOptions(new CSharpCompilationOptions( - OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Disable)); - return generatedCodeProject; - } - } -} diff --git a/src/AutoRest.CSharp/MgmtTest/Extensions/CodeWriterExtensions.cs b/src/AutoRest.CSharp/MgmtTest/Extensions/CodeWriterExtensions.cs deleted file mode 100644 index c65b0353c65..00000000000 --- a/src/AutoRest.CSharp/MgmtTest/Extensions/CodeWriterExtensions.cs +++ /dev/null @@ -1,565 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Xml; -using AutoRest.CSharp.Common.Input; -using AutoRest.CSharp.Common.Input.Examples; -using AutoRest.CSharp.Generation.Types; -using AutoRest.CSharp.Generation.Writers; -using AutoRest.CSharp.Mgmt.AutoRest; -using AutoRest.CSharp.Mgmt.Decorator; -using AutoRest.CSharp.MgmtTest.Models; -using AutoRest.CSharp.Output.Models.Shared; -using AutoRest.CSharp.Output.Models.Types; -using AutoRest.CSharp.Utilities; -using Azure; -using Azure.Core; -using Azure.Core.Expressions.DataFactory; - -namespace AutoRest.CSharp.MgmtTest.Extensions -{ - internal static class CodeWriterExtensions - { - /// - /// Write an ExampleValue, using the given type as a hint. - /// If the type is not provided, a type will be created from TypeFactory instead - /// In a case that a property's type is replaced, we will have to provide the actual type otherwise the type from TypeFactory will always be the one that is replaced. - /// - /// - /// - /// - /// - /// - public static CodeWriter AppendExampleValue(this CodeWriter writer, InputExampleValue exampleValue, CSharpType? type = null, bool includeCollectionInitialization = true) - { - // get the type of this schema in the type factory if the type is not specified - // get the type from TypeFactory cannot get the replaced types, therefore we need to put an argument in the signature as a hint in case this might happen in the replaced type case - type ??= MgmtContext.Context.TypeFactory.CreateType(exampleValue.Type); - - if (exampleValue.Type != null && ReferenceTypePropertyChooser.TryGetCachedExactMatch(exampleValue.Type, out CSharpType? replaceType) && replaceType != null) - type = replaceType; - - return type!.IsFrameworkType ? - writer.AppendFrameworkTypeValue(type, exampleValue, includeCollectionInitialization) : - writer.AppendTypeProviderValue(type, exampleValue); - } - - public static CodeWriter AppendExampleParameterValue(this CodeWriter writer, Parameter parameter, ExampleParameterValue exampleParameterValue) - { - // for optional parameter, we write the parameter name here - if (parameter.DefaultValue != null) - writer.Append($"{parameter.Name}: "); - - return writer.AppendExampleParameterValue(exampleParameterValue); - } - - public static CodeWriter AppendExamplePropertyBagParamValue(this CodeWriter writer, Parameter parameter, Dictionary exampleParameterValue) - { - writer.Append($"new {parameter.Type}("); - var mgmtObject = parameter.Type.Implementation as ModelTypeProvider; - var requiredProperties = mgmtObject!.Properties.Where(p => p.IsRequired); - var nonRequiredProperties = mgmtObject!.Properties.Where(p => !p.IsRequired); - foreach (var property in requiredProperties) - { - var parameterName = property.Declaration.Name.ToVariableName(); - if (exampleParameterValue.TryGetValue(parameterName, out ExampleParameterValue? value)) - { - writer.Append($"{parameterName}: "); - writer.AppendExampleParameterValue(value); - writer.Append($", "); - } - } - writer.RemoveTrailingComma(); - writer.Append($"){{ "); - foreach (var property in nonRequiredProperties) - { - var parameterName = property.Declaration.Name.ToVariableName(); - if (exampleParameterValue.TryGetValue(parameterName, out ExampleParameterValue? value)) - { - writer.Append($"{property.Declaration.Name} = "); - writer.AppendExampleParameterValue(value); - writer.Append($", "); - } - } - writer.RemoveTrailingComma(); - return writer.Append($"}}"); - } - - public static CodeWriter AppendExampleParameterValue(this CodeWriter writer, ExampleParameterValue exampleParameterValue) - { - if (exampleParameterValue.Value != null) - return writer.AppendExampleValue(exampleParameterValue.Value, exampleParameterValue.Type); - else - return writer.Append(exampleParameterValue.Expression!); - } - - private static CodeWriter AppendFrameworkTypeValue(this CodeWriter writer, CSharpType type, InputExampleValue exampleValue, bool includeCollectionInitialization = true) - { - if (type.IsList) - return writer.AppendListValue(type, exampleValue as InputExampleListValue, includeCollectionInitialization); - - if (type.IsDictionary) - return writer.AppendDictionaryValue(type, exampleValue as InputExampleObjectValue, includeCollectionInitialization); - - if (type.FrameworkType == typeof(BinaryData)) - { - switch (exampleValue) - { - case InputExampleObjectValue objectValue: - return writer.AppendBinaryData(objectValue); - case InputExampleRawValue rawValue: - return writer.AppendBinaryData(rawValue); - default: - throw new InvalidOperationException("Unhandled BinaryData example value type"); - } - } - - if (type.FrameworkType == typeof(DataFactoryElement<>)) - return writer.AppendDataFactoryElementValue(type, exampleValue); - - if (exampleValue.Type is InputModelType) - return writer.AppendComplexFrameworkTypeValue(type.FrameworkType, exampleValue); - - return writer.AppendRawValue((exampleValue as InputExampleRawValue)?.RawValue, type.FrameworkType, exampleValue.Type); - } - - private static CodeWriter AppendDataFactoryElementValue(this CodeWriter writer, CSharpType type, InputExampleValue exampleValue) - { - if (type.FrameworkType != typeof(DataFactoryElement<>)) - throw new ArgumentException("DataFactoryElement<> is expected but got: " + type.ToString()); - - const string DFE_OBJECT_SCHEMA_PREFIX = "DataFactoryElement"; - - if (exampleValue.Type is InputModelType inputModel && inputModel.Name.Equals(DFE_OBJECT_SCHEMA_PREFIX)) - { - const string DFE_OBJECT_PROPERTY_TYPE = "type"; - const string DFE_OBJECT_PROPERTY_VALUE = "value"; - - var exampleObjectValue = exampleValue as InputExampleObjectValue; - string dfeType = (string)(exampleObjectValue?.Values![DFE_OBJECT_PROPERTY_TYPE] as InputExampleRawValue)?.RawValue!; - InputExampleValue dfeValue = exampleObjectValue?.Values![DFE_OBJECT_PROPERTY_VALUE]!; - string createMethodName = dfeType switch - { - "Expression" => nameof(DataFactoryElement.FromExpression), - "SecureString" => nameof(DataFactoryElement.FromSecretString), - "AzureKeyVaultSecretReference" => nameof(DataFactoryElement.FromKeyVaultSecret), - _ => throw new InvalidOperationException("Unknown DataFactoryElement type: " + dfeType) - }; - - writer.Append($"{type: L}.{createMethodName}("); - writer.AppendExampleValue(dfeValue, typeof(DataFactoryKeyVaultSecret)); - writer.AppendRaw(")"); - } - else - { - CSharpType literlType = type.Arguments.First(); - writer.AppendExampleValue(exampleValue, literlType); - } - return writer; - } - - private static CodeWriter AppendListValue(this CodeWriter writer, CSharpType type, InputExampleListValue? exampleValue, bool includeInitialization = true) - { - // the collections in our generated SDK could never be assigned to, therefore if we have null value here, we can only assign an empty collection - var elements = exampleValue?.Values ?? Enumerable.Empty(); - // since this is a list, we take the first generic argument (and it should always has this first argument) - var elementType = type.Arguments.First(); - var initialization = includeInitialization ? (FormattableString)$"new {elementType}[]" : (FormattableString)$""; - using (writer.Scope(initialization, newLine: false)) - { - foreach (var itemValue in elements) - { - // TODO -- bad formatting will happen in collection initializer because roslyn formatter ignores things in these places: https://github.com/dotnet/roslyn/issues/8269 - writer.AppendExampleValue(itemValue, elementType); - if (type.IsFrameworkType) - writer.AppendRaw(","); - else - writer.LineRaw(","); - } - writer.RemoveTrailingComma(); - writer.Line(); - } - return writer; - } - - private static CodeWriter AppendDictionaryValue(this CodeWriter writer, CSharpType type, InputExampleObjectValue? exampleValue, bool includeInitialization = true) - { - // the collections in our generated SDK could never be assigned to, therefore if we have null value here, we can only assign an empty collection - var keyValues = exampleValue?.Values ?? new Dictionary(); - // since this is a dictionary, we take the first generic argument as the key type - // this is important because in our SDK, the key of a dictionary is not always a string. It could be a string-like type, for instance, a ResourceIdentifier - var keyType = type.Arguments[0]; - // the second as the value type - var valueType = type.Arguments[1]; - // the type of dictionary in our generated SDK is usually an interface `IDictionary<>` or `IReadOnlyDictionary<>`, here we just use `Dictionary` as its proper initialization - var concreteDictType = new CSharpType(typeof(Dictionary<,>), type.Arguments); - var initialization = includeInitialization ? (FormattableString)$"new {concreteDictType}()" : (FormattableString)$""; - using (writer.Scope(initialization, newLine: false)) - { - foreach ((var key, var value) in keyValues) - { - // write key - writer.AppendRaw("["); - writer.AppendExampleValue(new InputExampleRawValue(InputPrimitiveType.String, key), keyType); - writer.AppendRaw("] = "); - writer.AppendExampleValue(value, valueType); - writer.LineRaw(", "); - } - } - return writer; - } - - private static CodeWriter AppendBinaryData(this CodeWriter writer, InputExampleObjectValue exampleValue) - { - var method = "FromObjectAsJson"; - writer.Append($"{typeof(BinaryData)}.{method}("); - writer.AppendAnonymousObject(exampleValue); - return writer.AppendRaw(")"); - } - - private static CodeWriter AppendBinaryData(this CodeWriter writer, InputExampleRawValue exampleValue) - { - // determine which method on BinaryData we want to use to serialize this BinaryData - if (exampleValue.RawValue != null && exampleValue.RawValue is string strValue) - { - var method = "FromString"; - return writer.Append($"{typeof(BinaryData)}.{method}({"\"" + strValue + "\"":L})"); - } - else - { - var method = "FromObjectAsJson"; - writer.Append($"{typeof(BinaryData)}.{method}("); - writer.AppendAnonymousObject(exampleValue); - return writer.AppendRaw(")"); - } - } - - private static CodeWriter AppendComplexFrameworkTypeValue(this CodeWriter writer, Type type, InputExampleValue exampleValue) - { - if (exampleValue is not InputExampleObjectValue exampleObjectValue) - { - writer.AppendRaw(type.IsValueType ? "default" : "null"); - return writer; - } - var propertyMetadataDict = ReferenceClassFinder.GetPropertyMetadata(type); - // get the first constructor - var publicCtor = type.GetConstructors().Where(c => c.IsPublic).OrderBy(c => c.GetParameters().Count()).First(); - // find the required parameters and put it into the constructor - writer.Append($"new {type}("); - foreach (var parameter in publicCtor.GetParameters()) - { - // we here assume the parameter name is the same as the serialized name of the property. - if (exampleObjectValue.Values.TryGetValue(parameter.Name!, out var value)) - { - writer.AppendExampleValue(value, parameter.ParameterType); - writer.AppendRaw(","); - } - else - { - // when there is nothing matched, we could not do much but write a `default` as placeholder here. - writer.AppendRaw("default,"); - } - } - writer.RemoveTrailingComma(); - writer.AppendRaw(")"); - // assign values to the optional parameters - var optionalProperties = new Dictionary(); - foreach ((var propertyName, var metadata) in propertyMetadataDict) - { - if (metadata.Required) - continue; - // find if we have a value for this property - if (exampleObjectValue.Values.TryGetValue(propertyName, out var value)) - { - optionalProperties.Add(propertyName, value); - } - } - if (optionalProperties.Count > 0) - { - using (writer.Scope($"", newLine: false)) - { - foreach ((var propertyName, var value) in optionalProperties) - { - writer.Append($"{propertyName} = "); - writer.AppendExampleValue(value); - writer.LineRaw(","); - } - writer.RemoveTrailingComma(); - } - } - - return writer; - } - - private static CodeWriter AppendAnonymousObject(this CodeWriter writer, InputExampleValue exampleValue) - { - // check if this is simple type - if (exampleValue is InputExampleRawValue exampleRawValue) - { - return writer.AppendRawValue(exampleRawValue.RawValue, exampleRawValue.Type.GetType()); - } - // check if this is an array - if (exampleValue is InputExampleListValue exampleListValue) - { - return writer.AppendListValue(typeof(List), exampleListValue); - } - // fallback to complex object - if (exampleValue is InputExampleObjectValue exampleObjectValue) - { - using (writer.Scope($"new {typeof(Dictionary)}()")) - { - foreach ((var key, var value) in exampleObjectValue.Values) - { - writer.Append($"[{key:L}] = "); - writer.AppendAnonymousObject(value); - } - } - } - else - { - writer.LineRaw("null"); - } - - return writer; - } - - private static CodeWriter AppendRawList(this CodeWriter writer, List list) - { - writer.Append($"new {typeof(object)}[] {{ "); - foreach (var item in list) - { - writer.AppendRawValue(item, item?.GetType() ?? typeof(object)); - writer.AppendRaw(", "); - } - writer.RemoveTrailingComma(); - writer.AppendRaw(" }"); - return writer; - } - - private static CodeWriter AppendRawDictionary(this CodeWriter writer, Dictionary dict) - { - using (writer.Scope($"new {typeof(Dictionary)}()", newLine: false)) - { - foreach ((var key, var value) in dict) - { - writer.Append($"[{key.ToString():L}] = "); - writer.AppendRawValue(value, value?.GetType() ?? typeof(object)); - writer.LineRaw(","); - } - writer.RemoveTrailingComma(); - } - - return writer; - } - - private static CodeWriter AppendRawValue(this CodeWriter writer, object? rawValue, Type type, InputType? inputType = null) => rawValue switch - { - string str => writer.AppendStringValue(type, str, inputType), // we need this function to convert the string to real type. There might be a bug that some literal types (like bool and int) are deserialized to string - null => writer.AppendRaw("null"), - List list => writer.AppendRawList(list), - Dictionary dict => writer.AppendRawDictionary(dict), - _ when type == rawValue.GetType() => writer.Append($"{rawValue:L}"), - _ => writer.Append($"({type}){rawValue:L}") - }; - - private static CodeWriter AppendStringValue(this CodeWriter writer, Type type, string value, InputType? inputType) => type switch - { - _ when inputType is InputDurationType { Encode: DurationKnownEncoding.Iso8601 } => writer.Append($"{typeof(XmlConvert)}.ToTimeSpan({value:L})"), - _ when _newInstanceInitializedTypes.Contains(type) => writer.Append($"new {type}({value:L})"), - _ when _parsableInitializedTypes.Contains(type) => writer.Append($"{type}.Parse({value:L})"), - _ when type == typeof(byte[]) => writer.Append($"{typeof(Convert)}.FromBase64String({value:L})"), - _ => writer.Append($"{value:L}"), - }; - - private static bool IsStringLikeType(CSharpType type) => type.IsFrameworkType && (_newInstanceInitializedTypes.Contains(type.FrameworkType) || _parsableInitializedTypes.Contains(type.FrameworkType)) || type.Equals(typeof(string)); - - private static readonly HashSet _newInstanceInitializedTypes = new() - { - typeof(ResourceIdentifier), - typeof(ResourceType), - typeof(Uri), - typeof(AzureLocation), typeof(AzureLocation?), - typeof(RequestMethod), typeof(RequestMethod?), - typeof(ContentType), typeof(ContentType?), - typeof(ETag), typeof(ETag?) - }; - - private static readonly HashSet _parsableInitializedTypes = new() - { - typeof(DateTimeOffset), - typeof(Guid), typeof(Guid?), - typeof(TimeSpan), typeof(TimeSpan?), - typeof(IPAddress) - }; - - private static CodeWriter AppendTypeProviderValue(this CodeWriter writer, CSharpType type, InputExampleValue exampleValue) - { - switch (type.Implementation) - { - case ObjectType objectType: - return writer.AppendObjectTypeValue(objectType, (exampleValue as InputExampleObjectValue)?.Values); - case EnumType enumType: - return writer.AppendEnumTypeValue(enumType, (exampleValue as InputExampleRawValue)?.RawValue!); - } - return writer.AppendRaw("default"); - } - - private static ObjectType GetActualImplementation(ObjectType objectType, IReadOnlyDictionary valueDict) - { - var discriminator = objectType.Discriminator; - // check if this has a discriminator - if (discriminator == null || !discriminator.HasDescendants) - return objectType; - var discriminatorPropertyName = discriminator.SerializedName; - // get value of this in the valueDict and we should always has a discriminator value in the example - if (!valueDict.TryGetValue(discriminatorPropertyName, out var exampleValue) || exampleValue is not InputExampleRawValue exampleRawValue) - { - throw new InvalidOperationException($"Attempting to get the discriminator value for property `{discriminatorPropertyName}` on object type {objectType.Type.Name} but got none or non-primitive type"); - } - // the discriminator should always be a primitive type - var actualDiscriminatorValue = exampleRawValue.RawValue; - var implementation = discriminator.Implementations.FirstOrDefault(info => info.Key.Equals(actualDiscriminatorValue)); - if (implementation == null) - throw new InvalidOperationException($"Cannot find an implementation corresponding to the discriminator value {actualDiscriminatorValue} for object model type {objectType.Type.Name}"); - - return (ObjectType)implementation.Type.Implementation; - } - - private static CodeWriter AppendObjectTypeValue(this CodeWriter writer, ObjectType objectType, IReadOnlyDictionary? valueDict) - { - if (valueDict == null) - { - writer.AppendRaw("null"); - return writer; - } - // need to get the actual ObjectType if this type has a discrinimator - objectType = GetActualImplementation(objectType, valueDict); - // get all the properties on this type, including the properties from its base type. Distinct is needed when the type is replaced with additional property included - var properties = new HashSet(objectType.EnumerateHierarchy().SelectMany(objectType => objectType.Properties).DistinctBy(p => p.Declaration.Name)); - var constructor = objectType.InitializationConstructor; - writer.Append($"new {objectType.Type}("); - // build a map from parameter name to property - var propertyDict = properties.ToDictionary( - property => property.Declaration.Name.ToVariableName(), property => property); - // find the corresponding properties in the parameters - foreach (var parameter in constructor.Signature.Parameters) - { - // try every property, convert them to variable name and see if there are some of them matching - var property = propertyDict[parameter.Name]; - InputExampleValue? exampleValue; - if (!valueDict.TryGetValue(property.InputModelProperty!.SerializedName, out exampleValue)) - { - // we could only stand the case that the missing property here is a collection, in this case, we pass an empty collection - if (property.Declaration.Type.IsCollection) - { - exampleValue = new InputExampleRawValue(property.InputModelProperty!.Type, null); - } - else if (IsStringLikeType(property.Declaration.Type)) - { - // this is a patch that some parameter is not marked as required, but in our generated code, it inherits from ResourceData, in which location is in the constructor and our code will recognize it as required - exampleValue = new InputExampleRawValue(InputPrimitiveType.String, "placeholder"); - } - else - throw new InvalidOperationException($"Example value for required property {property.InputModelProperty.SerializedName} in class {objectType.Type.Name} is not found"); - } - properties.Remove(property); - writer.AppendExampleValue(exampleValue, type: property.Declaration.Type).AppendRaw(","); - } - writer.RemoveTrailingComma(); - writer.AppendRaw(")"); - var propertiesToWrite = GetPropertiesToWrite(properties, valueDict); - if (propertiesToWrite.Count > 0) // only write the property initializers when there are properties to write - { - using (writer.Scope($"", newLine: false)) - { - foreach ((var propertyName, (var propertyType, var exampleValue)) in propertiesToWrite) - { - writer.Append($"{propertyName} = "); - // we need to pass in the current type of this property to make sure its initialization is correct - writer.AppendExampleValue(exampleValue, type: propertyType, includeCollectionInitialization: false); - writer.LineRaw(","); - } - } - } - return writer; - } - - private static Dictionary GetPropertiesToWrite(IEnumerable properties, IReadOnlyDictionary valueDict) - { - var propertiesToWrite = new Dictionary(); - foreach (var property in properties) - { - var propertyToDeal = property; - var inputModelProperty = propertyToDeal.InputModelProperty; - if (inputModelProperty == null) - continue; // now we explicitly ignore all the AdditionalProperties - - if (!valueDict.TryGetValue(inputModelProperty.SerializedName, out var exampleValue)) - continue; // skip the property that does not have a value - - // check if this property is safe-flattened - var flattenedProperty = propertyToDeal.FlattenedProperty; - if (flattenedProperty != null) - { - // unwrap the single property object - exampleValue = UnwrapExampleValueFromSinglePropertySchema(exampleValue, flattenedProperty); - if (exampleValue == null) - continue; - propertyToDeal = flattenedProperty; - } - - if (!IsPropertyAssignable(propertyToDeal)) - continue; // now we explicitly ignore all the AdditionalProperties - - propertiesToWrite.Add(propertyToDeal.Declaration.Name, (propertyToDeal.Declaration.Type, exampleValue)); - } - - return propertiesToWrite; - } - - private static InputExampleValue? UnwrapExampleValueFromSinglePropertySchema(InputExampleValue exampleValue, FlattenedObjectTypeProperty flattenedProperty) - { - var hierarchyStack = flattenedProperty.BuildHierarchyStack(); - // reverse the stack because it is a stack, iterating it will start from the innerest property - // skip the first because this stack include the property we are handling here right now - foreach (var property in hierarchyStack.Reverse().Skip(1)) - { - var inputModelProperty = property.InputModelProperty; - if (exampleValue is not InputExampleObjectValue exampleObjectValue || !exampleObjectValue.Values.TryGetValue(inputModelProperty!.SerializedName, out var inner)) - return null; - // get the value of this layer - exampleValue = inner; - } - return exampleValue; - } - - private static bool IsPropertyAssignable(ObjectTypeProperty property) - => property.Declaration.Accessibility == "public" && (property.Declaration.Type.IsReadWriteDictionary || property.Declaration.Type.IsReadWriteList || !property.IsReadOnly); - - private static CodeWriter AppendEnumTypeValue(this CodeWriter writer, EnumType enumType, object value) - { - // find value in one of the choices. - // Here we convert the values to string then compare, because the raw value has the "primitive types are deserialized into strings" issue - var choice = enumType.Values.FirstOrDefault(c => StringComparer.Ordinal.Equals(value.ToString(), c.Value.Value?.ToString())); - writer.UseNamespace(enumType.Type.Namespace); - if (choice != null) - return writer.Append($"{enumType.Type.Name}.{choice.Declaration.Name}"); - // if we did not find a match, check if this is a SealedChoice, if so, we throw exceptions - if (!enumType.IsExtensible) - throw new InvalidOperationException($"Enum value `{value}` in example does not find in type {enumType.Type.Name}"); - var underlyingType = enumType.ValueType.FrameworkType; // the underlying type of an extensible enum should always be a primitive type which is a framework type - return writer.Append($"new {enumType.Type}(") - .AppendRawValue(value, underlyingType) - .AppendRaw(")"); - } - - public static CodeWriter AppendDeclaration(this CodeWriter writer, CodeWriterVariableDeclaration declaration) - { - return writer.Append($"{declaration.Type} {declaration.Declaration:D}"); - } - } -} diff --git a/src/AutoRest.CSharp/MgmtTest/Generation/MgmtTestWriterBase.cs b/src/AutoRest.CSharp/MgmtTest/Generation/MgmtTestWriterBase.cs deleted file mode 100644 index e5b8c309281..00000000000 --- a/src/AutoRest.CSharp/MgmtTest/Generation/MgmtTestWriterBase.cs +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using System.Linq; -using AutoRest.CSharp.Common.Input; -using AutoRest.CSharp.Generation.Types; -using AutoRest.CSharp.Generation.Writers; -using AutoRest.CSharp.Mgmt.Models; -using AutoRest.CSharp.Mgmt.Output; -using AutoRest.CSharp.MgmtTest.Extensions; -using AutoRest.CSharp.MgmtTest.Models; -using AutoRest.CSharp.MgmtTest.Output; -using AutoRest.CSharp.Utilities; -using Azure.Core; -using Azure.ResourceManager; -using Azure.ResourceManager.Resources; - -namespace AutoRest.CSharp.MgmtTest.Generation -{ - internal abstract class MgmtTestWriterBase where TProvider : MgmtTestProvider - { - protected CodeWriter _writer; - - protected TProvider This { get; } - - protected MgmtTestWriterBase(TProvider provider) : this(new CodeWriter(), provider) - { - } - - protected MgmtTestWriterBase(CodeWriter writer, TProvider provider) - { - _writer = writer; - This = provider; - } - - public abstract void Write(); - - protected virtual void WriteClassDeclaration() - { - _writer.WriteXmlDocumentationSummary(This.Description); - _writer.Append($"{This.Accessibility} partial class {This.Type.Name}"); - if (This.BaseType != null) - { - _writer.Append($" : {This.BaseType:D}"); - } - _writer.Line(); - } - - protected virtual void WriteCreateResourceIdentifier(OperationExample example, CodeWriterDeclaration idDeclaration, RequestPath resourcePath, CSharpType resourceType) - { - var resourceIdExpressionValues = example.ComposeResourceIdentifierExpressionValues(resourcePath).ToList(); - foreach (var initializer in resourceIdExpressionValues) - { - if (initializer.ScopeValues is not null) - { - foreach (var value in initializer.ScopeValues) - { - var parameterDeclaration = new CodeWriterVariableDeclaration(value.Name, value.Type); - _writer.AppendDeclaration(parameterDeclaration).AppendRaw(" = ") - .AppendExampleParameterValue(value).LineRaw(";"); - } - } - } - _writer.Append($"{typeof(ResourceIdentifier)} {idDeclaration:D} = {resourceType}.CreateResourceIdentifier("); - foreach (var initializer in resourceIdExpressionValues) - { - if (initializer.Value is not null) - _writer.AppendExampleParameterValue(initializer.Value).AppendRaw(","); - else - { - _writer.AppendRaw("$\"").AppendRaw(initializer.Scope!.ToString()!).AppendRaw("\"").AppendRaw(","); - } - } - _writer.RemoveTrailingComma(); - _writer.Line($");"); - } - - protected virtual void WriteCreateScopeResourceIdentifier(OperationExample example, CodeWriterDeclaration declaration, RequestPath requestPath) - { - var resourceIdExpressionValues = example.ComposeResourceIdentifierExpressionValues(requestPath).ToList(); - foreach (var initializer in resourceIdExpressionValues) - { - if (initializer.ScopeValues is not null) - { - foreach (var value in initializer.ScopeValues) - { - var parameterDeclaration = new CodeWriterVariableDeclaration(value.Name, value.Type); - _writer.AppendDeclaration(parameterDeclaration).AppendRaw(" = ") - .AppendExampleParameterValue(value).LineRaw(";"); - } - } - } - _writer.Append($"{typeof(ResourceIdentifier)} {declaration:D} = new {typeof(ResourceIdentifier)}("); - // we do not know exactly which resource the scope is, therefore we need to use the string.Format method to include those parameter values and construct a valid resource id of the scope - _writer.Append($"{typeof(string)}.Format(\""); - int refIndex = 0; - foreach (var segment in requestPath) - { - _writer.AppendRaw("/"); - if (segment.IsConstant) - _writer.AppendRaw(segment.ConstantValue); - else - _writer.Append($"{{{refIndex++}}}"); - } - _writer.AppendRaw("\", "); - foreach (var initializer in resourceIdExpressionValues) - { - if (initializer.Value is not null) - _writer.AppendExampleParameterValue(initializer.Value).AppendRaw(","); - else - { - _writer.AppendRaw("$\"").AppendRaw(initializer.Scope!.ToString()!).AppendRaw("\"").AppendRaw(","); - } - } - _writer.RemoveTrailingComma(); - _writer.LineRaw("));"); - } - - protected CodeWriterDeclaration WriteGetResource(MgmtTypeProvider carrierResource, OperationExample example, FormattableString client) - => carrierResource switch - { - ResourceCollection => throw new InvalidOperationException($"ResourceCollection is not supported here"), - Resource parentResource => WriteGetFromResource(parentResource, example, client), - MgmtExtension parentExtension => WriteGetExtension(parentExtension, example, client), - _ => throw new InvalidOperationException($"Unknown parent {carrierResource.GetType()}"), - }; - - protected CodeWriterDeclaration WriteGetFromResource(Resource carrierResource, OperationExample example, FormattableString client) - { - // Can't use CSharpType.Equals(typeof(...)) because the CSharpType.Equals(Type) would assume itself is a FrameworkType, but here it's generated when IsArmCore=true - if (Configuration.MgmtConfiguration.IsArmCore && carrierResource.Type.Name == nameof(TenantResource)) - { - return WriteGetTenantResource(carrierResource, example, client); - } - else - { - var idVar = new CodeWriterDeclaration($"{carrierResource.Type.Name}Id".ToVariableName()); - WriteCreateResourceIdentifier(example, idVar, carrierResource.RequestPath, carrierResource.Type); - var resourceVar = new CodeWriterDeclaration(carrierResource.ResourceName.ToVariableName()); - _writer.Line($"{carrierResource.Type} {resourceVar:D} = {client}.Get{carrierResource.Type.Name}({idVar});"); - - return resourceVar; - } - } - - protected CodeWriterDeclaration WriteGetExtension(MgmtExtension parentExtension, OperationExample example, FormattableString client) => parentExtension.ArmCoreType switch - { - _ when parentExtension.ArmCoreType == typeof(TenantResource) => WriteGetTenantResource(parentExtension, example, client), - _ when parentExtension.ArmCoreType == typeof(ArmResource) => WriteForArmResourceExtension(parentExtension, example, client), - _ => WriteGetOtherExtension(parentExtension, example, client) - }; - - private CodeWriterDeclaration WriteForArmResourceExtension(MgmtTypeProvider parentExtension, OperationExample example, FormattableString client) - { - // For Extension against ArmResource the operation will be re-formatted to Operation(this ArmClient, ResourceIdentifier scope, ...) - // so just return armclient here and the scope part will be handled when generate the operation invoke code - - // we should have defined the ArmClient before, try to figure it out from the formattableString instead of creating a new one - var clientVar = client.GetArguments()?.FirstOrDefault(a => a is CodeWriterDeclaration d && d.RequestedName == "client") as CodeWriterDeclaration; - if (clientVar == null) - throw new InvalidOperationException("Failed to figure out ArmClient Var for calling ArmResource Extension method"); - return clientVar; - } - - private CodeWriterDeclaration WriteGetTenantResource(MgmtTypeProvider parentExtension, OperationExample example, FormattableString client) - { - var resourceVar = new CodeWriterDeclaration(parentExtension.ResourceName.ToVariableName()); - _writer.Line($"var {resourceVar:D} = {client}.GetTenants().GetAllAsync().GetAsyncEnumerator().Current;"); - // since right after we get the resource above, we would immeditately call an extension method on the resource - // here we just add the namespace of the extension class into the writer so that the following invocation would not have compilation errors - _writer.UseNamespace(parentExtension.Namespace); - return resourceVar; - } - - private CodeWriterDeclaration WriteGetOtherExtension(MgmtExtension parentExtension, OperationExample example, FormattableString client) - { - var resourceVar = new CodeWriterDeclaration(parentExtension.ResourceName.ToVariableName()); - var idVar = new CodeWriterDeclaration($"{parentExtension.ArmCoreType.Name}Id".ToVariableName()); - WriteCreateResourceIdentifier(example, idVar, parentExtension.ContextualPath, parentExtension.ArmCoreType); - - _writer.Line($"{parentExtension.ArmCoreType} {resourceVar:D} = {client}.Get{parentExtension.ArmCoreType.Name}({idVar});"); - // since right after we get the resource above, we would immeditately call an extension method on the resource - // here we just add the namespace of the extension class into the writer so that the following invocation would not have compilation errors - _writer.UseNamespace(parentExtension.Namespace); - return resourceVar; - } - - public override string ToString() - { - return _writer.ToString(); - } - - protected string CreateMethodName(string methodName, bool async = true) - { - return async ? $"{methodName}Async" : methodName; - } - } -} diff --git a/src/AutoRest.CSharp/MgmtTest/Generation/Samples/MgmtSampleWriter.cs b/src/AutoRest.CSharp/MgmtTest/Generation/Samples/MgmtSampleWriter.cs deleted file mode 100644 index 0b78ee6cb11..00000000000 --- a/src/AutoRest.CSharp/MgmtTest/Generation/Samples/MgmtSampleWriter.cs +++ /dev/null @@ -1,616 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using AutoRest.CSharp.Common.Input; -using AutoRest.CSharp.Generation.Types; -using AutoRest.CSharp.Generation.Writers; -using AutoRest.CSharp.Mgmt.Decorator; -using AutoRest.CSharp.Mgmt.Models; -using AutoRest.CSharp.Mgmt.Output; -using AutoRest.CSharp.MgmtTest.Extensions; -using AutoRest.CSharp.MgmtTest.Models; -using AutoRest.CSharp.MgmtTest.Output.Samples; -using AutoRest.CSharp.Output.Models.Shared; -using Azure; -using Azure.Core; -using Azure.ResourceManager; -using Azure.ResourceManager.Resources; - -namespace AutoRest.CSharp.MgmtTest.Generation.Samples -{ - internal class MgmtSampleWriter : MgmtTestWriterBase - { - public MgmtSampleWriter(MgmtSampleProvider sample) : base(sample) - { - } - - public override void Write() - { - using (_writer.Namespace(This.Namespace)) - { - WriteClassDeclaration(); - using (_writer.Scope()) - { - WriteImplementation(); - } - } - } - - private void WriteImplementation() - { - foreach (var sample in This.Samples) - { - WriteSample(sample); - _writer.Line(); - } - } - - private readonly Dictionary _sampleMethods = new(); - - private void WriteSample(Sample sample) - { - var signature = sample.GetMethodSignature(false); - if (_sampleMethods.TryGetValue(signature.Name, out var count)) - { - _sampleMethods[signature.Name]++; - signature = signature with - { - Name = $"{signature.Name}{count}", // we never care the name of the method that is enclosing the sample implementation. Our sample fetching pipeline only takes the content. - }; - } - else - { - _sampleMethods.Add(signature.Name, 1); - } - - // write the attributes - _writer.UseNamespace("NUnit.Framework"); - _writer.Line($"[Test]"); - _writer.Line($"[Ignore(\"Only validating compilation of examples\")]"); - using (_writer.WriteMethodDeclaration(signature)) - { - WriteSampleSteps(sample); - } - } - - private void WriteSampleSteps(Sample sample) - { - // Write sample source file - _writer.Line($"// Generated from example definition: {sample.ExampleFilepath}"); - // Write claimers - _writer.Line($"// this example is just showing the usage of \"{sample.OperationId}\" operation, for the dependent resources, they will have to be created separately."); - _writer.Line(); - - // Write the ArmClient and authentication - var clientStepResult = WriteGetArmClient(); - - // Write the operation invocation - var result = sample.Carrier switch - { - ResourceCollection collection => WriteSampleOperationForResourceCollection(clientStepResult, collection, sample), - Resource resource => WriteSampleOperationForResource(clientStepResult, resource, sample), - MgmtExtension extension => WriteSampleOperationForExtension(clientStepResult, extension, sample), - _ => throw new InvalidOperationException("Should never happen"), - }; - - // Write the result handling - WriteResultHandling(result); - } - - private void WriteResultHandling(CodeWriterVariableDeclaration? result, bool newLine = true) - { - if (newLine) - _writer.Line(); - - if (result == null) - { - _writer.Line($"{typeof(Console)}.WriteLine(\"Succeeded\");"); - } - else - { - if (result.Type.IsNullable) - { - using (_writer.Scope($"if({result.Declaration} == null)")) - { - _writer.Line($"{typeof(Console)}.WriteLine(\"Succeeded with null as result\");"); - } - using (_writer.Scope($"else")) - { - WriteNotNullResultHandling(result); - } - } - else - { - WriteNotNullResultHandling(result); - } - } - } - - private void WriteNotNullResultHandling(CodeWriterVariableDeclaration result) - { - if (result.Type is { IsFrameworkType: false, Implementation: Resource resource }) - { - WriteResourceResultHandling(result, resource); - } - else if (result.Type is { IsFrameworkType: false, Implementation: ResourceData resourceData }) - { - WriteResourceDataResultHandling(result, resourceData); - } - else - { - WriteOtherResultHandling(result); - } - } - - private void WriteResourceResultHandling(CodeWriterVariableDeclaration result, Resource resource) - { - // create a data variable for this data - _writer.Line($"// the variable {result.Declaration} is a resource, you could call other operations on this instance as well"); - _writer.Line($"// but just for demo, we get its data from this resource instance"); - var dataResult = new CodeWriterVariableDeclaration("resourceData", resource.ResourceData.Type); - _writer.AppendDeclaration(dataResult) - .Line($" = {result.Declaration}.Data;"); - - // handle the data - WriteResourceDataResultHandling(dataResult, resource.ResourceData); - } - - private void WriteResourceDataResultHandling(CodeWriterVariableDeclaration result, ResourceData resourceData) - { - _writer.Line($"// for demo we just print out the id"); - _writer.Line($"{typeof(Console)}.WriteLine($\"Succeeded on id: {{{result.Declaration}.Id}}\");"); - } - - private void WriteOtherResultHandling(CodeWriterVariableDeclaration result) - { - if (result.Type.IsFrameworkType) - { - _writer.Line($"{typeof(Console)}.WriteLine($\"Succeeded: {{{result.Declaration}}}\");"); - } - else - { - _writer.Line($"{typeof(Console)}.WriteLine($\"Succeeded: {{{result.Declaration}}}\");"); - } - } - - private CodeWriterVariableDeclaration WriteGetArmClient() - { - _writer.LineRaw("// get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line"); - var cred = new CodeWriterVariableDeclaration("cred", typeof(TokenCredential)); - _writer.UseNamespace("Azure.Identity"); - _writer.AppendDeclaration(cred) - .Line($" = new DefaultAzureCredential();"); - _writer.Line($"// authenticate your client"); - var clientResult = new CodeWriterVariableDeclaration("client", typeof(ArmClient)); - _writer.AppendDeclaration(clientResult) - .Line($" = new {typeof(ArmClient)}({cred.Declaration});"); - - return clientResult; - } - - private string GetResourceName(MgmtTypeProvider provider) => provider switch - { - Resource resource => resource.Type.Name, - MgmtExtension extension => extension.ArmCoreType.Name, - _ => throw new InvalidOperationException("Should never happen") - }; - - private CodeWriterVariableDeclaration? WriteSampleOperationForResourceCollection(CodeWriterVariableDeclaration clientResult, ResourceCollection collection, Sample sample) - { - _writer.Line(); - - var collectionResult = WriteGetCollection(clientResult, collection, sample); - var result = WriteSampleOperation(collectionResult, sample); - - return result; - } - - private CodeWriterVariableDeclaration? WriteSampleOperationForResource(CodeWriterVariableDeclaration clientVar, Resource resource, Sample sample) - { - _writer.Line(); - - var resourceName = GetResourceName(resource); - _writer.Line($"// this example assumes you already have this {resourceName} created on azure"); - _writer.Line($"// for more information of creating {resourceName}, please refer to the document of {resourceName}"); - var resourceResult = WriteGetResource(resource, sample, $"{clientVar.Declaration}"); - var result = WriteSampleOperation(new CodeWriterVariableDeclaration(resourceResult, resource.Type), sample); - - return result; - } - - private CodeWriterVariableDeclaration? WriteSampleOperationForExtension(CodeWriterVariableDeclaration clientVar, MgmtExtension extension, Sample sample) - { - _writer.Line(); - - var resourceName = GetResourceName(extension); - if (extension is not ArmResourceExtension) - { - // the method will be available on client directly for ArmResourceExtension's operations, so dont need these comment in that case - _writer.Line($"// this example assumes you already have this {resourceName} created on azure"); - _writer.Line($"// for more information of creating {resourceName}, please refer to the document of {resourceName}"); - } - var resourceResult = WriteGetExtension(extension, sample, $"{clientVar.Declaration}"); - var result = WriteSampleOperation(new CodeWriterVariableDeclaration(resourceResult, extension.ArmCoreType), sample); - - return result; - } - - private CodeWriterDeclaration? WriteGetParentResource(MgmtTypeProvider parent, Sample testCase, FormattableString clientExpression) - { - if (parent is MgmtExtension extension && extension.ArmCoreType == typeof(ArmResource)) - return null; - - return WriteGetResource(parent, testCase, clientExpression); - } - - private CodeWriterVariableDeclaration WriteGetCollectionWithoutParent(CodeWriterVariableDeclaration clientResult, ResourceCollection collection) - { - CodeWriterVariableDeclaration col = new CodeWriterVariableDeclaration("collection", collection.Type); - // Can't use CSharpType.Equals(typeof(...)) because the CSharpType.Equals(Type) would assume itself is a FrameworkType, but here it's generated when IsArmCore=true - if (Configuration.MgmtConfiguration.IsArmCore && collection.Type.Name == nameof(TenantCollection)) - _writer.Line($"{col.Type} {col.Declaration:D} = {clientResult.Declaration}.GetTenants();"); - else - // TODO: add support when we found any other case - throw new NotSupportedException("Unsupported type to get collection without parent: " + collection.Type.Name); - return col; - } - - private CodeWriterVariableDeclaration WriteGetCollection(CodeWriterVariableDeclaration clientResult, ResourceCollection collection, Sample sample) - { - var parent = sample.Parent; - - if (parent == null) - // i.e. Tenant doesnt have parent - return WriteGetCollectionWithoutParent(clientResult, collection); - - var parentName = GetResourceName(parent); - _writer.Line($"// this example assumes you already have this {parentName} created on azure"); - _writer.Line($"// for more information of creating {parentName}, please refer to the document of {parentName}"); - var parentVar = WriteGetParentResource(parent, sample, $"{clientResult.Declaration}"); - - var resourceName = collection.Resource.ResourceName; - // now we have the parent resource, get the collection from that resource - // TODO -- we might should look this up inside the code project for correct method name - var getResourceCollectionMethodName = $"Get{resourceName.ResourceNameToPlural()}"; - var collectionResult = new CodeWriterVariableDeclaration("collection", collection.Type); - - _writer.Line(); - _writer.Line($"// get the collection of this {collection.Resource.Type.Name}"); - - var idVar = new CodeWriterDeclaration("scopeId"); - if (parentVar == null) - { - // this case will happen only when the resource is a scope resource - WriteCreateScopeResourceIdentifier(sample, idVar, sample.RequestPath.GetScopePath()); - } - // first find the variables we need and write their assignments - var parameters = new Dictionary(); - foreach (var extraParameter in collection.ExtraConstructorParameters) - { - if (sample.ParameterValueMapping.TryGetValue(extraParameter.Name, out var value)) - { - var declaration = new CodeWriterVariableDeclaration(extraParameter.Name, extraParameter.Type); - parameters.Add(extraParameter, declaration); - - _writer.AppendDeclaration(declaration) - .AppendRaw(" = ") - .AppendExampleParameterValue(value) - .LineRaw(";"); - } - } - _writer.AppendDeclaration(collectionResult).AppendRaw(" = "); - if (parentVar == null) - { - // Can't use CSharpType.Equals(typeof(...)) because the CSharpType.Equals(Type) would assume itself is a FrameworkType, but here it's generated when IsArmCore=true - if (Configuration.MgmtConfiguration.IsArmCore && parent.Type.Name == nameof(ArmResource)) - { - // Retrive the generic resource first for the methods of ArmResource directly which don't have extnsion methods under ArmClient - _writer.Append($"{clientResult.Declaration}.GetGenericResource({idVar}).{getResourceCollectionMethodName}("); - } - else - { - _writer.Append($"{clientResult.Declaration}.{getResourceCollectionMethodName}({idVar}, "); - } - } - else - { - _writer.Append($"{parentVar}.{getResourceCollectionMethodName}("); - } - - // iterate over the parameter list and put them into the invocation - foreach ((var parameter, var declaration) in parameters) - { - _writer.AppendIf($"{parameter.Name}: ", parameter.DefaultValue != null) - .Append($"{declaration.Declaration}") - .AppendRaw(","); - } - _writer.RemoveTrailingComma(); - _writer.LineRaw(");"); - - _writer.Line(); - - return collectionResult; - } - - private CodeWriterVariableDeclaration? WriteSampleOperation(CodeWriterVariableDeclaration collectionResult, Sample sample) - { - if (sample.IsLro) - { - return WriteSampleLroOperation(collectionResult.Declaration, sample); - } - else if (sample.IsPageable) - { - return WriteSamplePageableOperation(collectionResult.Declaration, sample); - } - - return WriteSampleNormalOperation(collectionResult.Declaration, sample); - } - - private CodeWriterVariableDeclaration? WriteSampleLroOperation(CodeWriterDeclaration instanceVar, Sample sample) - { - _writer.Line(); - _writer.Line($"// invoke the operation"); - // if the Lro is an ArmOperation - var parameters = WriteOperationInvocationParameters(sample); - var lroType = sample.Operation.ReturnType; - if (lroType.IsGenericType) - { - var lroResult = new CodeWriterVariableDeclaration("lro", sample.Operation.ReturnType); - _writer.AppendDeclaration(lroResult).AppendRaw(" = "); - // write the method invocation - WriteOperationInvocation(instanceVar, parameters, sample); - var valueResult = new CodeWriterVariableDeclaration("result", lroType.Arguments.First()); - _writer.AppendDeclaration(valueResult) - .Line($"= {lroResult.Declaration}.Value;"); - - return valueResult; - } - else - { - // if the Lro is an ArmOperation without body, we just write the method invocation without assignment - WriteOperationInvocation(instanceVar, parameters, sample); - return null; - } - } - - private CodeWriterVariableDeclaration? WriteSampleNormalOperation(CodeWriterDeclaration instanceVar, Sample sample) - { - _writer.Line(); - _writer.Line($"// invoke the operation"); - var parameters = WriteOperationInvocationParameters(sample); - var returnType = sample.Operation.ReturnType; - if (returnType.IsGenericType) - { - // if the type is NullableResponse, there is no implicit convert, so have to explicitly unwrap it - if (returnType.IsFrameworkType && returnType.FrameworkType == typeof(NullableResponse<>)) - { - var unwrappedReturnType = returnType.Arguments.First().WithNullable(true); - var valueResponse = new CodeWriterVariableDeclaration(Configuration.ApiTypes.ResponseParameterName, returnType); - _writer.AppendDeclaration(valueResponse).AppendRaw(" = "); - // write the method invocation - WriteOperationInvocation(instanceVar, parameters, sample); - // unwrap the response - var valueResult = new CodeWriterVariableDeclaration("result", unwrappedReturnType); - _writer.AppendDeclaration(valueResult).AppendRaw(" = ") - .Line($"{valueResponse.Declaration}.HasValue ? {valueResponse.Declaration}.Value : null;"); - return valueResult; - - } - else - { - // an operation with a response - var unwrappedReturnType = returnType.Arguments.First(); - // if the type inside Response is a generic type, somehow the implicit convert Response => T does not work, we have to explicitly unwrap it - if (unwrappedReturnType.IsGenericType) - { - var valueResponse = new CodeWriterVariableDeclaration(Configuration.ApiTypes.ResponseParameterName, returnType); - _writer.AppendDeclaration(valueResponse).AppendRaw(" = "); - // write the method invocation - WriteOperationInvocation(instanceVar, parameters, sample); - // unwrap the response - var valueResult = new CodeWriterVariableDeclaration("result", unwrappedReturnType); - _writer.AppendDeclaration(valueResult).AppendRaw(" = ") - .Line($"{valueResponse.Declaration}.Value;"); - return valueResult; - } - else // if it is a type provider type, we could rely on the implicit convert Response => T - { - var valueResult = new CodeWriterVariableDeclaration("result", unwrappedReturnType); - _writer.AppendDeclaration(valueResult).AppendRaw(" = "); - // write the method invocation - WriteOperationInvocation(instanceVar, parameters, sample); - return valueResult; - } - } - } - else - { - // an operation without a response - WriteOperationInvocation(instanceVar, parameters, sample); - return null; - } - } - - private CodeWriterVariableDeclaration? WriteSamplePageableOperation(CodeWriterDeclaration instanceVar, Sample sample) - { - _writer.Line(); - _writer.Line($"// invoke the operation and iterate over the result"); - var parameters = WriteOperationInvocationParameters(sample); - // when the operation is pageable, the return type refers to the type of the item T, instead of Pageable - var itemResult = new CodeWriterVariableDeclaration("item", sample.Operation.ReturnType); - _writer.Append($"await foreach (") - .AppendDeclaration(itemResult) - .AppendRaw(" in "); - - WriteOperationInvocation(instanceVar, parameters, sample, isEndOfLine: false); - using (_writer.Scope($")")) - { - WriteResultHandling(itemResult, newLine: false); - } - - // an invocation of a pageable operation does not return a result - return null; - } - - private Dictionary WriteOperationInvocationParameters(Sample sample) - { - var result = new Dictionary(); - foreach (var parameter in sample.Operation.MethodParameters) - { - // some parameters are always inline - if (IsInlineParameter(parameter)) - continue; - - if (sample.Carrier is ArmResourceExtension && parameter.Type.Equals(typeof(ArmResource))) - { - // this is an extension operation against ArmResource - // For Extension against ArmResource the operation will be re-formatted to Operation(this ArmClient, ResourceIdentifier scope, ...) - // so insert a scope parameter instead of ArmResource here - var scope = new CodeWriterVariableDeclaration("scope", new CSharpType(typeof(ResourceIdentifier))); - WriteCreateScopeResourceIdentifier(sample, scope.Declaration, sample.RequestPath.GetScopePath()); - result.Add(parameter.Name, scope); - } - - if (sample.ParameterValueMapping.TryGetValue(parameter.Name, out var parameterValue)) - { - var declaration = new CodeWriterVariableDeclaration(parameter.Name, parameter.Type); - _writer.AppendDeclaration(declaration).AppendRaw(" = ") - .AppendExampleParameterValue(parameterValue).LineRaw(";"); - result.Add(parameter.Name, declaration); - } - - else if (parameter.IsPropertyBag) - { - var declaration = new CodeWriterVariableDeclaration(parameter.Name, parameter.Type); - _writer.AppendDeclaration(declaration).AppendRaw(" = ") - .AppendExamplePropertyBagParamValue(parameter, sample.PropertyBagParamValueMapping).LineRaw(";"); - result.Add(parameter.Name, declaration); - } - } - - return result; - } - - private static readonly HashSet InlineParameters = new() { KnownParameters.WaitForCompletion, KnownParameters.CancellationTokenParameter }; - - private static bool IsInlineParameter(Parameter parameter) - => InlineParameters.Contains(parameter); - - private void WriteOperationInvocation(CodeWriterDeclaration instanceVar, Dictionary parameters, Sample sample, bool isEndOfLine = true, bool isAsync = true) - { - var methodName = CreateMethodName(sample.Operation.Name); - _writer.AppendIf($"await ", isAsync && !sample.Operation.IsPagingOperation) // paging operation never needs this await - .Append($"{instanceVar}.{methodName}("); - foreach (var parameter in sample.Operation.MethodParameters) - { - if (IsInlineParameter(parameter)) - { - if (sample.ParameterValueMapping.TryGetValue(parameter.Name, out var value)) - { - _writer.AppendExampleParameterValue(parameter, value).AppendRaw(","); - } - continue; - } - if (parameters.TryGetValue(parameter.Name, out var declaration)) - { - _writer.AppendIf($"{parameter.Name}: ", parameter.DefaultValue != null) - .Append($"{declaration.Declaration}") - .AppendRaw(","); - } - } - _writer.RemoveTrailingComma(); - _writer.AppendRaw(")").LineRawIf(";", isEndOfLine); - } - - protected override void WriteCreateResourceIdentifier(OperationExample example, CodeWriterDeclaration idDeclaration, RequestPath requestPath, CSharpType resourceType) - { - var parameters = new List(); - foreach (var value in example.ComposeResourceIdentifierExpressionValues(requestPath)) - { - var declaration = new CodeWriterVariableDeclaration(value.Name, value.Type); - if (value.Value is not null) - { - _writer.AppendDeclaration(declaration) - .AppendRaw(" = ").AppendExampleParameterValue(value.Value).LineRaw(";"); - } - else - { - // first write the variables - foreach (var parameterValue in value.ScopeValues!) - { - var parameterDeclaration = new CodeWriterVariableDeclaration(parameterValue.Name, parameterValue.Type); - _writer.AppendDeclaration(parameterDeclaration) - .AppendRaw(" = ").AppendExampleParameterValue(parameterValue).LineRaw(";"); - } - // then write the scope - _writer.AppendDeclaration(declaration).AppendRaw(" = ") - .AppendRaw("$\"") - .AppendRaw(value.Scope!.ToString()!) - .LineRaw("\";"); - } - - parameters.Add(declaration); - } - _writer.Append($"{typeof(ResourceIdentifier)} {idDeclaration:D} = {resourceType}.CreateResourceIdentifier("); - foreach (var parameter in parameters) - { - _writer.Append($"{parameter.Declaration}").AppendRaw(","); - } - _writer.RemoveTrailingComma(); - _writer.Line($");"); - } - - protected override void WriteCreateScopeResourceIdentifier(OperationExample example, CodeWriterDeclaration idDeclaration, RequestPath requestPath) - { - var parameters = new List(); - foreach (var value in example.ComposeResourceIdentifierExpressionValues(requestPath)) - { - var declaration = new CodeWriterVariableDeclaration(value.Name, value.Type); - if (value.Value is not null) - { - _writer.AppendDeclaration(declaration) - .AppendRaw(" = ").AppendExampleParameterValue(value.Value).LineRaw(";"); - } - else - { - // first write the variables - foreach (var parameterValue in value.ScopeValues!) - { - var parameterDeclaration = new CodeWriterVariableDeclaration(parameterValue.Name, parameterValue.Type); - _writer.AppendDeclaration(parameterDeclaration) - .AppendRaw(" = ").AppendExampleParameterValue(parameterValue).LineRaw(";"); - } - // then write the scope - _writer.AppendDeclaration(declaration).AppendRaw(" = ") - .AppendRaw("$\"") - .AppendRaw(value.Scope!.ToString()!) - .LineRaw("\";"); - } - - parameters.Add(declaration); - } - _writer.Append($"{typeof(ResourceIdentifier)} {idDeclaration:D} = new {typeof(ResourceIdentifier)}("); - // we do not know exactly which resource the scope is, therefore we need to use the string.Format method to include those parameter values and construct a valid resource id of the scope - _writer.Append($"{typeof(string)}.Format(\""); - int refIndex = 0; - foreach (var segment in requestPath) - { - _writer.AppendRaw("/"); - if (segment.IsConstant) - _writer.AppendRaw(segment.ConstantValue); - else - _writer.Append($"{{{refIndex++}}}"); - } - _writer.AppendRaw("\", "); - foreach (var parameter in parameters) - { - _writer.Append($"{parameter.Declaration}").AppendRaw(","); - } - _writer.RemoveTrailingComma(); - _writer.LineRaw("));"); - } - } -} diff --git a/src/AutoRest.CSharp/MgmtTest/Models/CodeWriterVariableDeclaration.cs b/src/AutoRest.CSharp/MgmtTest/Models/CodeWriterVariableDeclaration.cs deleted file mode 100644 index 748af78c5f3..00000000000 --- a/src/AutoRest.CSharp/MgmtTest/Models/CodeWriterVariableDeclaration.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License - -using AutoRest.CSharp.Generation.Types; -using AutoRest.CSharp.Generation.Writers; - -namespace AutoRest.CSharp.MgmtTest.Models -{ - internal record CodeWriterVariableDeclaration(CodeWriterDeclaration Declaration, CSharpType Type) - { - public CodeWriterVariableDeclaration(string name, CSharpType type) : this(new CodeWriterDeclaration(name), type) - { } - } -} diff --git a/src/AutoRest.CSharp/MgmtTest/Models/MgmtTypeProviderAndOperation.cs b/src/AutoRest.CSharp/MgmtTest/Models/MgmtTypeProviderAndOperation.cs deleted file mode 100644 index fd0c7000db7..00000000000 --- a/src/AutoRest.CSharp/MgmtTest/Models/MgmtTypeProviderAndOperation.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using AutoRest.CSharp.Mgmt.Models; -using AutoRest.CSharp.Mgmt.Output; - -namespace AutoRest.CSharp.MgmtTest.Models -{ - internal record MgmtTypeProviderAndOperation(MgmtTypeProvider Carrier, MgmtClientOperation Operation); -} diff --git a/src/AutoRest.CSharp/MgmtTest/Models/OperationExample.cs b/src/AutoRest.CSharp/MgmtTest/Models/OperationExample.cs deleted file mode 100644 index 62ba772ffd9..00000000000 --- a/src/AutoRest.CSharp/MgmtTest/Models/OperationExample.cs +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using AutoRest.CSharp.Common.Input; -using AutoRest.CSharp.Common.Input.Examples; -using AutoRest.CSharp.Generation.Types; -using AutoRest.CSharp.Mgmt.Decorator; -using AutoRest.CSharp.Mgmt.Models; -using AutoRest.CSharp.Mgmt.Output; -using AutoRest.CSharp.Output.Models.Requests; - -namespace AutoRest.CSharp.MgmtTest.Models -{ - internal class OperationExample - { - private readonly Lazy> _parameterNameToSerializedNameMapping; - - internal protected InputOperationExample _example; - internal protected InputOperation _inputOperation; - public string OperationId { get; } - public string Name => _example.Name!; - - public MgmtTypeProvider Carrier { get; } - - /// - /// The Owner of this Operation means which test class this test operation will go into - /// if the provider is a resource, the owner is the resource (this includes the ResourceCollection). Otherwise, for instance the extensions, use the Operation.Resource as its owner. Use the Carrier as a fallback - /// - public MgmtTypeProvider Owner => Carrier is Resource ? Carrier : (Operation.Resource ?? Carrier); - public MgmtClientOperation Operation { get; } - - private MgmtRestOperation? _restOperation; - public MgmtRestOperation RestOperation => _restOperation ??= GetRestOperationFromOperationId(); - public RequestPath RequestPath => RestOperation.RequestPath; - - /// - /// All the parameters defined in this test case - /// We do not need to distiguish between ClientParameters and MethodParameters because we usually change that in code model transformation - /// - public IEnumerable AllParameters => _example.Parameters; - private IEnumerable? _pathParameters; - public IEnumerable PathParameters => _pathParameters ??= AllParameters.Where(p => p.Parameter.Location == RequestLocation.Path); - - protected OperationExample(string operationId, MgmtTypeProvider carrier, MgmtClientOperation operation, InputOperation inputOperation, InputOperationExample example) - { - OperationId = operationId; - _example = example; - _inputOperation = inputOperation; - Carrier = carrier; - Operation = operation; - _parameterNameToSerializedNameMapping = new Lazy>(EnsureParameterSerializedNames); - } - - private MgmtRestOperation GetRestOperationFromOperationId() - { - foreach (var operation in Operation) - { - if (operation.OperationId == OperationId) - return operation; - } - - throw new InvalidOperationException($"Cannot find operationId {OperationId} in example {_inputOperation.Name}"); - } - - /// - /// Returns the values to construct a resource identifier for the input request path of the resource - /// This method does not validate the parenting relationship between the request path passing in and the request path inside this test case - /// The passing in request path should always be a parent of the request path in this test case - /// - /// - /// - public IEnumerable ComposeResourceIdentifierExpressionValues(RequestPath resourcePath) - { - var scopePath = resourcePath.GetScopePath(); - if (scopePath.IsRawParameterizedScope()) - { - var trimmedPath = resourcePath.TrimScope(); - return ComposeResourceIdentifierForScopePath(scopePath, trimmedPath); - } - else - { - return ComposeResourceIdentifierForUsualPath(RequestPath, resourcePath); - } - } - - private IEnumerable ComposeResourceIdentifierForScopePath(RequestPath scopePath, RequestPath trimmedPath) - { - // we need to find the scope, and put everything in the scope into the scope parameter - var operationScopePath = RequestPath.GetScopePath(); - var operationTrimmedPath = RequestPath.TrimScope(); - - var scopeValues = new List(); - foreach (var referenceSegment in operationScopePath.Where(segment => segment.IsReference)) - { - scopeValues.Add(FindExampleParameterValueFromReference(referenceSegment.Reference)); - } - - if (operationScopePath.Count == 1) - yield return new ResourceIdentifierInitializer(scopeValues.Single()); - else - yield return new ResourceIdentifierInitializer(operationScopePath, scopeValues); - - foreach (var referenceSegment in operationTrimmedPath.Take(trimmedPath.Count).Where(segment => segment.IsReference)) - { - yield return new ResourceIdentifierInitializer(FindExampleParameterValueFromReference(referenceSegment.Reference)); - } - } - - private IEnumerable ComposeResourceIdentifierForUsualPath(RequestPath requestPath, RequestPath resourcePath) - { - // try to figure out ref segments from requestPath according the ones from resource Path - // Dont match the path side-by-side because - // 1. there is a case that the parameter names are different - // 2. the path structure may be different totally when customized, - // i.e. in ResourceManager, parent of /subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName} - // is configured to /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace} - var myRefs = requestPath.Where(s => s.IsReference); - var resourceRefCount = resourcePath.Where(s => s.IsReference).Count(); - return myRefs.Take(resourceRefCount).Select(refSeg => new ResourceIdentifierInitializer(FindExampleParameterValueFromReference(refSeg.Reference))); - } - - private ExampleParameterValue FindExampleParameterValueFromReference(Reference reference) - { - // find a path parameter in our path parameters for one with same name - var serializedName = GetParameterSerializedName(reference.Name); - var parameter = FindPathExampleParameterBySerializedName(serializedName); - - return new ExampleParameterValue(reference, parameter.ExampleValue); - } - - private Dictionary EnsureParameterSerializedNames() - { - var result = new Dictionary(StringComparer.OrdinalIgnoreCase); - - foreach (var requestParameter in _inputOperation.Parameters) - { - result.Add(requestParameter.Name, requestParameter.NameInRequest ?? requestParameter.Name); - } - - return result; - } - - protected string GetParameterSerializedName(string name) => _parameterNameToSerializedNameMapping.Value[name]; - - private InputParameterExample FindPathExampleParameterBySerializedName(string serializedName) - { - var parameter = FindExampleParameterBySerializedName(PathParameters, serializedName); - - // we throw exceptions here because path parameter cannot be optional, therefore if we do not find a parameter in the example, there must be an issue in the example - if (parameter == null) - throw new InvalidOperationException($"Cannot find a parameter in test case {_inputOperation.Name} with the name of {serializedName}"); - - return parameter; - } - - protected InputParameterExample? FindExampleParameterBySerializedName(IEnumerable parameters, string name) - => parameters.FirstOrDefault(p => p.Parameter.NameInRequest == name); - } -} diff --git a/src/AutoRest.CSharp/MgmtTest/Models/ResourceIdentifierInitializer.cs b/src/AutoRest.CSharp/MgmtTest/Models/ResourceIdentifierInitializer.cs deleted file mode 100644 index a7ec358a995..00000000000 --- a/src/AutoRest.CSharp/MgmtTest/Models/ResourceIdentifierInitializer.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Text; -using AutoRest.CSharp.Generation.Types; -using AutoRest.CSharp.Mgmt.Models; -using Azure.Core; - -namespace AutoRest.CSharp.MgmtTest.Models -{ - internal class ResourceIdentifierInitializer - { - public IEnumerable? ScopeValues { get; } - - public RequestPath? Scope { get; } - - public ExampleParameterValue? Value { get; } - - public string Name { get; } - - public CSharpType Type { get; } - - public ResourceIdentifierInitializer(RequestPath scope, IEnumerable values) - { - Name = "scope"; - Type = typeof(string); - Scope = scope; - ScopeValues = values; - } - - public ResourceIdentifierInitializer(ExampleParameterValue value) - { - Name = value.Name; - Type = value.Type; - Value = value; - } - } -} diff --git a/src/AutoRest.CSharp/MgmtTest/Output/Samples/MgmtSampleProvider.cs b/src/AutoRest.CSharp/MgmtTest/Output/Samples/MgmtSampleProvider.cs deleted file mode 100644 index ac0c46b1407..00000000000 --- a/src/AutoRest.CSharp/MgmtTest/Output/Samples/MgmtSampleProvider.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using AutoRest.CSharp.Mgmt.Output; -using AutoRest.CSharp.MgmtTest.Models; - -namespace AutoRest.CSharp.MgmtTest.Output.Samples -{ - internal class MgmtSampleProvider : MgmtTestProvider - { - public MgmtTypeProvider Owner { get; } - public IEnumerable Samples { get; } - - public MgmtSampleProvider(MgmtTypeProvider owner, IEnumerable samples) : base() - { - Owner = owner; - Samples = samples; - } - - private string? _defaultName; - protected override string DefaultName => _defaultName ??= $"Sample_{Owner.Type.Name}"; - - protected override string DefaultNamespace => $"{Owner.Type.Namespace}.Samples"; - - // a sample class does not need a description - public override FormattableString Description => $""; - } -} diff --git a/test/TestProjects/MgmtMockAndSample/specification/mockSwagger/examples/resources/CalculateTemplateHashWithQueryParameters.json b/test/TestProjects/MgmtMockAndSample/specification/mockSwagger/examples/resources/CalculateTemplateHashWithQueryParameters.json index 8da8b5ebdf2..598116b3390 100644 --- a/test/TestProjects/MgmtMockAndSample/specification/mockSwagger/examples/resources/CalculateTemplateHashWithQueryParameters.json +++ b/test/TestProjects/MgmtMockAndSample/specification/mockSwagger/examples/resources/CalculateTemplateHashWithQueryParameters.json @@ -49,4 +49,4 @@ } } } -} \ No newline at end of file +} diff --git a/test/TestProjects/MgmtMockAndSample/src/Generated/Configuration.json b/test/TestProjects/MgmtMockAndSample/src/Generated/Configuration.json index b2e2ad84339..673f56b3c82 100644 --- a/test/TestProjects/MgmtMockAndSample/src/Generated/Configuration.json +++ b/test/TestProjects/MgmtMockAndSample/src/Generated/Configuration.json @@ -45,12 +45,16 @@ "PrivilegedOperations": { "Vaults_CreateOrUpdate": "Test for privileged operations configuration" }, + "RawParameterizedScopes": [ + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}" + ], "sample-gen": { - "SkippedOperations": [ + "skipped-operations": [ "Vaults_GetDeleted", "Vaults_Update" ], - "Sample": true + "sample": true, + "output-folder": "..\\..\\tests\\Generated" }, "flavor": "azure", "generate-test-project": true, diff --git a/test/TestProjects/MgmtMockAndSample/src/readme.md b/test/TestProjects/MgmtMockAndSample/src/readme.md index c59336fdbc5..b759dfe2963 100644 --- a/test/TestProjects/MgmtMockAndSample/src/readme.md +++ b/test/TestProjects/MgmtMockAndSample/src/readme.md @@ -25,7 +25,6 @@ modelerfour: include-x-ms-examples-original-file: false sample-gen: - mock: true sample: true output-folder: $(this-folder)../tests/Generated clear-output-folder: true diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_DiskEncryptionSetCollection.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_DiskEncryptionSetCollection.cs index 40e7ac33775..f991384bbf8 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_DiskEncryptionSetCollection.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_DiskEncryptionSetCollection.cs @@ -44,7 +44,7 @@ public async Task CreateOrUpdate_CreateADiskEncryptionSetWithKeyVaultFromADiffer // invoke the operation string diskEncryptionSetName = "myDiskEncryptionSet"; - DiskEncryptionSetData data = new DiskEncryptionSetData() + DiskEncryptionSetData data = new DiskEncryptionSetData { Identity = new ManagedServiceIdentity("SystemAssigned"), EncryptionType = DiskEncryptionSetType.EncryptionAtRestWithCustomerKey, @@ -85,13 +85,13 @@ public async Task CreateOrUpdate_CreateADiskEncryptionSetWithKeyVaultFromADiffer // invoke the operation string diskEncryptionSetName = "myDiskEncryptionSet"; - DiskEncryptionSetData data = new DiskEncryptionSetData() + DiskEncryptionSetData data = new DiskEncryptionSetData { Identity = new ManagedServiceIdentity("UserAssigned") { UserAssignedIdentities = { -[new ResourceIdentifier("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}")] = new UserAssignedIdentity(), +[new ResourceIdentifier("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}")] = new UserAssignedIdentity() }, }, EncryptionType = DiskEncryptionSetType.EncryptionAtRestWithCustomerKey, @@ -132,7 +132,7 @@ public async Task CreateOrUpdate_CreateADiskEncryptionSet() // invoke the operation string diskEncryptionSetName = "myDiskEncryptionSet"; - DiskEncryptionSetData data = new DiskEncryptionSetData() + DiskEncryptionSetData data = new DiskEncryptionSetData { Identity = new ManagedServiceIdentity("SystemAssigned"), EncryptionType = DiskEncryptionSetType.EncryptionAtRestWithCustomerKey, @@ -186,7 +186,7 @@ public async Task Get_GetInformationAboutADiskEncryptionSetWhenAutoKeyRotationFa [Test] [Ignore("Only validating compilation of examples")] - public async Task Exists_GetInformationAboutADiskEncryptionSetWhenAutoKeyRotationFailed() + public async Task Get_GetInformationAboutADiskEncryptionSet() { // Generated from example definition: // this example is just showing the usage of "DiskEncryptionSets_Get" operation, for the dependent resources, they will have to be created separately. @@ -208,17 +208,21 @@ public async Task Exists_GetInformationAboutADiskEncryptionSetWhenAutoKeyRotatio // invoke the operation string diskEncryptionSetName = "myDiskEncryptionSet"; - bool result = await collection.ExistsAsync(diskEncryptionSetName); + DiskEncryptionSetResource result = await collection.GetAsync(diskEncryptionSetName); - Console.WriteLine($"Succeeded: {result}"); + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + DiskEncryptionSetData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetIfExists_GetInformationAboutADiskEncryptionSetWhenAutoKeyRotationFailed() + public async Task GetAll_ListAllDiskEncryptionSetsInAResourceGroup() { // Generated from example definition: - // this example is just showing the usage of "DiskEncryptionSets_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "DiskEncryptionSets_ListByResourceGroup" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -235,28 +239,22 @@ public async Task GetIfExists_GetInformationAboutADiskEncryptionSetWhenAutoKeyRo // get the collection of this DiskEncryptionSetResource DiskEncryptionSetCollection collection = resourceGroupResource.GetDiskEncryptionSets(); - // invoke the operation - string diskEncryptionSetName = "myDiskEncryptionSet"; - NullableResponse response = await collection.GetIfExistsAsync(diskEncryptionSetName); - DiskEncryptionSetResource result = response.HasValue ? response.Value : null; - - if (result == null) - { - Console.WriteLine("Succeeded with null as result"); - } - else + // invoke the operation and iterate over the result + await foreach (DiskEncryptionSetResource item in collection.GetAllAsync()) { - // the variable result is a resource, you could call other operations on this instance as well + // the variable item is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - DiskEncryptionSetData resourceData = result.Data; + DiskEncryptionSetData resourceData = item.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } + + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetInformationAboutADiskEncryptionSet() + public async Task Exists_GetInformationAboutADiskEncryptionSetWhenAutoKeyRotationFailed() { // Generated from example definition: // this example is just showing the usage of "DiskEncryptionSets_Get" operation, for the dependent resources, they will have to be created separately. @@ -278,13 +276,9 @@ public async Task Get_GetInformationAboutADiskEncryptionSet() // invoke the operation string diskEncryptionSetName = "myDiskEncryptionSet"; - DiskEncryptionSetResource result = await collection.GetAsync(diskEncryptionSetName); + bool result = await collection.ExistsAsync(diskEncryptionSetName); - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - DiskEncryptionSetData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + Console.WriteLine($"Succeeded: {result}"); } [Test] @@ -318,7 +312,7 @@ public async Task Exists_GetInformationAboutADiskEncryptionSet() [Test] [Ignore("Only validating compilation of examples")] - public async Task GetIfExists_GetInformationAboutADiskEncryptionSet() + public async Task GetIfExists_GetInformationAboutADiskEncryptionSetWhenAutoKeyRotationFailed() { // Generated from example definition: // this example is just showing the usage of "DiskEncryptionSets_Get" operation, for the dependent resources, they will have to be created separately. @@ -359,10 +353,10 @@ public async Task GetIfExists_GetInformationAboutADiskEncryptionSet() [Test] [Ignore("Only validating compilation of examples")] - public async Task GetAll_ListAllDiskEncryptionSetsInAResourceGroup() + public async Task GetIfExists_GetInformationAboutADiskEncryptionSet() { // Generated from example definition: - // this example is just showing the usage of "DiskEncryptionSets_ListByResourceGroup" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "DiskEncryptionSets_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -379,17 +373,23 @@ public async Task GetAll_ListAllDiskEncryptionSetsInAResourceGroup() // get the collection of this DiskEncryptionSetResource DiskEncryptionSetCollection collection = resourceGroupResource.GetDiskEncryptionSets(); - // invoke the operation and iterate over the result - await foreach (DiskEncryptionSetResource item in collection.GetAllAsync()) + // invoke the operation + string diskEncryptionSetName = "myDiskEncryptionSet"; + NullableResponse response = await collection.GetIfExistsAsync(diskEncryptionSetName); + DiskEncryptionSetResource result = response.HasValue ? response.Value : null; + + if (result == null) { - // the variable item is a resource, you could call other operations on this instance as well + Console.WriteLine("Succeeded with null as result"); + } + else + { + // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - DiskEncryptionSetData resourceData = item.Data; + DiskEncryptionSetData resourceData = result.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } - - Console.WriteLine("Succeeded"); } } } diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_DiskEncryptionSetResource.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_DiskEncryptionSetResource.cs index 2057297c1a2..db91852b6de 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_DiskEncryptionSetResource.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_DiskEncryptionSetResource.cs @@ -12,7 +12,6 @@ using Azure.Identity; using Azure.ResourceManager; using Azure.ResourceManager.Models; -using Azure.ResourceManager.Resources; using MgmtMockAndSample.Models; using NUnit.Framework; @@ -22,10 +21,10 @@ public partial class Sample_DiskEncryptionSetResource { [Test] [Ignore("Only validating compilation of examples")] - public async Task Update_UpdateADiskEncryptionSetWithRotationToLatestKeyVersionEnabledSetToTrueSucceeded() + public async Task Get_GetInformationAboutADiskEncryptionSetWhenAutoKeyRotationFailed() { // Generated from example definition: - // this example is just showing the usage of "DiskEncryptionSets_Update" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "DiskEncryptionSets_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -41,15 +40,7 @@ public async Task Update_UpdateADiskEncryptionSetWithRotationToLatestKeyVersionE DiskEncryptionSetResource diskEncryptionSet = client.GetDiskEncryptionSetResource(diskEncryptionSetResourceId); // invoke the operation - DiskEncryptionSetPatch patch = new DiskEncryptionSetPatch() - { - Identity = new ManagedServiceIdentity("SystemAssigned"), - EncryptionType = DiskEncryptionSetType.EncryptionAtRestWithCustomerKey, - ActiveKey = new KeyForDiskEncryptionSet(new Uri("https://myvaultdifferentsub.vault-int.azure-int.net/keys/keyName/keyVersion1")), - RotationToLatestKeyVersionEnabled = true, - }; - ArmOperation lro = await diskEncryptionSet.UpdateAsync(WaitUntil.Completed, patch); - DiskEncryptionSetResource result = lro.Value; + DiskEncryptionSetResource result = await diskEncryptionSet.GetAsync(); // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance @@ -60,10 +51,10 @@ public async Task Update_UpdateADiskEncryptionSetWithRotationToLatestKeyVersionE [Test] [Ignore("Only validating compilation of examples")] - public async Task Update_UpdateADiskEncryptionSetWithRotationToLatestKeyVersionEnabledSetToTrueUpdating() + public async Task Get_GetInformationAboutADiskEncryptionSet() { // Generated from example definition: - // this example is just showing the usage of "DiskEncryptionSets_Update" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "DiskEncryptionSets_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -79,15 +70,7 @@ public async Task Update_UpdateADiskEncryptionSetWithRotationToLatestKeyVersionE DiskEncryptionSetResource diskEncryptionSet = client.GetDiskEncryptionSetResource(diskEncryptionSetResourceId); // invoke the operation - DiskEncryptionSetPatch patch = new DiskEncryptionSetPatch() - { - Identity = new ManagedServiceIdentity("SystemAssigned"), - EncryptionType = DiskEncryptionSetType.EncryptionAtRestWithCustomerKey, - ActiveKey = new KeyForDiskEncryptionSet(new Uri("https://myvaultdifferentsub.vault-int.azure-int.net/keys/keyName/keyVersion1")), - RotationToLatestKeyVersionEnabled = true, - }; - ArmOperation lro = await diskEncryptionSet.UpdateAsync(WaitUntil.Completed, patch); - DiskEncryptionSetResource result = lro.Value; + DiskEncryptionSetResource result = await diskEncryptionSet.GetAsync(); // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance @@ -98,10 +81,10 @@ public async Task Update_UpdateADiskEncryptionSetWithRotationToLatestKeyVersionE [Test] [Ignore("Only validating compilation of examples")] - public async Task Update_UpdateADiskEncryptionSet() + public async Task Delete_DeleteADiskEncryptionSet() { // Generated from example definition: - // this example is just showing the usage of "DiskEncryptionSets_Update" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "DiskEncryptionSets_Delete" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -117,35 +100,17 @@ public async Task Update_UpdateADiskEncryptionSet() DiskEncryptionSetResource diskEncryptionSet = client.GetDiskEncryptionSetResource(diskEncryptionSetResourceId); // invoke the operation - DiskEncryptionSetPatch patch = new DiskEncryptionSetPatch() - { - Tags = -{ -["department"] = "Development", -["project"] = "Encryption", -}, - EncryptionType = DiskEncryptionSetType.EncryptionAtRestWithCustomerKey, - ActiveKey = new KeyForDiskEncryptionSet(new Uri("https://myvmvault.vault-int.azure-int.net/keys/keyName/keyVersion")) - { - SourceVaultId = new ResourceIdentifier("/subscriptions/{subscriptionId}/resourceGroups/myResourceGroup/providers/Microsoft.KeyVault/vaults/myVMVault"), - }, - }; - ArmOperation lro = await diskEncryptionSet.UpdateAsync(WaitUntil.Completed, patch); - DiskEncryptionSetResource result = lro.Value; + await diskEncryptionSet.DeleteAsync(WaitUntil.Completed); - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - DiskEncryptionSetData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetInformationAboutADiskEncryptionSetWhenAutoKeyRotationFailed() + public async Task Update_UpdateADiskEncryptionSetWithRotationToLatestKeyVersionEnabledSetToTrueSucceeded() { // Generated from example definition: - // this example is just showing the usage of "DiskEncryptionSets_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "DiskEncryptionSets_Update" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -161,7 +126,15 @@ public async Task Get_GetInformationAboutADiskEncryptionSetWhenAutoKeyRotationFa DiskEncryptionSetResource diskEncryptionSet = client.GetDiskEncryptionSetResource(diskEncryptionSetResourceId); // invoke the operation - DiskEncryptionSetResource result = await diskEncryptionSet.GetAsync(); + DiskEncryptionSetPatch patch = new DiskEncryptionSetPatch + { + Identity = new ManagedServiceIdentity("SystemAssigned"), + EncryptionType = DiskEncryptionSetType.EncryptionAtRestWithCustomerKey, + ActiveKey = new KeyForDiskEncryptionSet(new Uri("https://myvaultdifferentsub.vault-int.azure-int.net/keys/keyName/keyVersion1")), + RotationToLatestKeyVersionEnabled = true, + }; + ArmOperation lro = await diskEncryptionSet.UpdateAsync(WaitUntil.Completed, patch); + DiskEncryptionSetResource result = lro.Value; // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance @@ -172,10 +145,10 @@ public async Task Get_GetInformationAboutADiskEncryptionSetWhenAutoKeyRotationFa [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetInformationAboutADiskEncryptionSet() + public async Task Update_UpdateADiskEncryptionSetWithRotationToLatestKeyVersionEnabledSetToTrueUpdating() { // Generated from example definition: - // this example is just showing the usage of "DiskEncryptionSets_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "DiskEncryptionSets_Update" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -191,7 +164,15 @@ public async Task Get_GetInformationAboutADiskEncryptionSet() DiskEncryptionSetResource diskEncryptionSet = client.GetDiskEncryptionSetResource(diskEncryptionSetResourceId); // invoke the operation - DiskEncryptionSetResource result = await diskEncryptionSet.GetAsync(); + DiskEncryptionSetPatch patch = new DiskEncryptionSetPatch + { + Identity = new ManagedServiceIdentity("SystemAssigned"), + EncryptionType = DiskEncryptionSetType.EncryptionAtRestWithCustomerKey, + ActiveKey = new KeyForDiskEncryptionSet(new Uri("https://myvaultdifferentsub.vault-int.azure-int.net/keys/keyName/keyVersion1")), + RotationToLatestKeyVersionEnabled = true, + }; + ArmOperation lro = await diskEncryptionSet.UpdateAsync(WaitUntil.Completed, patch); + DiskEncryptionSetResource result = lro.Value; // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance @@ -202,10 +183,10 @@ public async Task Get_GetInformationAboutADiskEncryptionSet() [Test] [Ignore("Only validating compilation of examples")] - public async Task Delete_DeleteADiskEncryptionSet() + public async Task Update_UpdateADiskEncryptionSet() { // Generated from example definition: - // this example is just showing the usage of "DiskEncryptionSets_Delete" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "DiskEncryptionSets_Update" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -221,40 +202,27 @@ public async Task Delete_DeleteADiskEncryptionSet() DiskEncryptionSetResource diskEncryptionSet = client.GetDiskEncryptionSetResource(diskEncryptionSetResourceId); // invoke the operation - await diskEncryptionSet.DeleteAsync(WaitUntil.Completed); - - Console.WriteLine("Succeeded"); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task GetDiskEncryptionSets_ListAllDiskEncryptionSetsInASubscription() - { - // Generated from example definition: - // this example is just showing the usage of "DiskEncryptionSets_List" operation, for the dependent resources, they will have to be created separately. - - // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line - TokenCredential cred = new DefaultAzureCredential(); - // authenticate your client - ArmClient client = new ArmClient(cred); - - // this example assumes you already have this SubscriptionResource created on azure - // for more information of creating SubscriptionResource, please refer to the document of SubscriptionResource - string subscriptionId = "{subscription-id}"; - ResourceIdentifier subscriptionResourceId = SubscriptionResource.CreateResourceIdentifier(subscriptionId); - SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); - - // invoke the operation and iterate over the result - await foreach (DiskEncryptionSetResource item in subscriptionResource.GetDiskEncryptionSetsAsync()) + DiskEncryptionSetPatch patch = new DiskEncryptionSetPatch { - // the variable item is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - DiskEncryptionSetData resourceData = item.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } + Tags = +{ +["department"] = "Development", +["project"] = "Encryption" +}, + EncryptionType = DiskEncryptionSetType.EncryptionAtRestWithCustomerKey, + ActiveKey = new KeyForDiskEncryptionSet(new Uri("https://myvmvault.vault-int.azure-int.net/keys/keyName/keyVersion")) + { + SourceVaultId = new ResourceIdentifier("/subscriptions/{subscriptionId}/resourceGroups/myResourceGroup/providers/Microsoft.KeyVault/vaults/myVMVault"), + }, + }; + ArmOperation lro = await diskEncryptionSet.UpdateAsync(WaitUntil.Completed, patch); + DiskEncryptionSetResource result = lro.Value; - Console.WriteLine("Succeeded"); + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + DiskEncryptionSetData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } } } diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyCollection.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyCollection.cs index 51465f17926..810e5f80842 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyCollection.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyCollection.cs @@ -20,109 +20,6 @@ namespace MgmtMockAndSample.Samples { public partial class Sample_FirewallPolicyCollection { - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Get_GetFirewallPolicy() - { - // Generated from example definition: - // this example is just showing the usage of "FirewallPolicies_Get" operation, for the dependent resources, they will have to be created separately. - - // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line - TokenCredential cred = new DefaultAzureCredential(); - // authenticate your client - ArmClient client = new ArmClient(cred); - - // this example assumes you already have this ResourceGroupResource created on azure - // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource - string subscriptionId = "subid"; - string resourceGroupName = "rg1"; - ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); - ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); - - // get the collection of this FirewallPolicyResource - FirewallPolicyCollection collection = resourceGroupResource.GetFirewallPolicies(); - - // invoke the operation - string firewallPolicyName = "firewallPolicy"; - FirewallPolicyResource result = await collection.GetAsync(firewallPolicyName); - - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - FirewallPolicyData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Exists_GetFirewallPolicy() - { - // Generated from example definition: - // this example is just showing the usage of "FirewallPolicies_Get" operation, for the dependent resources, they will have to be created separately. - - // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line - TokenCredential cred = new DefaultAzureCredential(); - // authenticate your client - ArmClient client = new ArmClient(cred); - - // this example assumes you already have this ResourceGroupResource created on azure - // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource - string subscriptionId = "subid"; - string resourceGroupName = "rg1"; - ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); - ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); - - // get the collection of this FirewallPolicyResource - FirewallPolicyCollection collection = resourceGroupResource.GetFirewallPolicies(); - - // invoke the operation - string firewallPolicyName = "firewallPolicy"; - bool result = await collection.ExistsAsync(firewallPolicyName); - - Console.WriteLine($"Succeeded: {result}"); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task GetIfExists_GetFirewallPolicy() - { - // Generated from example definition: - // this example is just showing the usage of "FirewallPolicies_Get" operation, for the dependent resources, they will have to be created separately. - - // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line - TokenCredential cred = new DefaultAzureCredential(); - // authenticate your client - ArmClient client = new ArmClient(cred); - - // this example assumes you already have this ResourceGroupResource created on azure - // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource - string subscriptionId = "subid"; - string resourceGroupName = "rg1"; - ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); - ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); - - // get the collection of this FirewallPolicyResource - FirewallPolicyCollection collection = resourceGroupResource.GetFirewallPolicies(); - - // invoke the operation - string firewallPolicyName = "firewallPolicy"; - NullableResponse response = await collection.GetIfExistsAsync(firewallPolicyName); - FirewallPolicyResource result = response.HasValue ? response.Value : null; - - if (result == null) - { - Console.WriteLine("Succeeded with null as result"); - } - else - { - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - FirewallPolicyData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } - } - [Test] [Ignore("Only validating compilation of examples")] public async Task CreateOrUpdate_CreateFirewallPolicy() @@ -149,7 +46,7 @@ public async Task CreateOrUpdate_CreateFirewallPolicy() string firewallPolicyName = "firewallPolicy"; FirewallPolicyData data = new FirewallPolicyData(new AzureLocation("West US")) { - StartupProbe = null, + StartupProbe = default, ReadinessProbe = new Probe(false) { InitialDelaySeconds = 30, @@ -157,88 +54,58 @@ public async Task CreateOrUpdate_CreateFirewallPolicy() FailureThreshold = 3, }, DesiredStatusCode = DesiredStatusCode.TwoHundredTwo, - ThreatIntelWhitelist = new FirewallPolicyThreatIntelWhitelist() + ThreatIntelWhitelist = new FirewallPolicyThreatIntelWhitelist { - IpAddresses = -{ -IPAddress.Parse("20.3.4.5") -}, - Fqdns = -{ -"*.microsoft.com" -}, + IpAddresses = { IPAddress.Parse("20.3.4.5") }, + Fqdns = { "*.microsoft.com" }, }, - Insights = new FirewallPolicyInsights() + Insights = new FirewallPolicyInsights { IsEnabled = true, RetentionDays = 100, - LogAnalyticsResources = new FirewallPolicyLogAnalyticsResources() + LogAnalyticsResources = new FirewallPolicyLogAnalyticsResources { - Workspaces = -{ -new FirewallPolicyLogAnalyticsWorkspace() + Workspaces = {new FirewallPolicyLogAnalyticsWorkspace { Region = "westus", WorkspaceIdId = new ResourceIdentifier("/subscriptions/subid/resourcegroups/rg1/providers/microsoft.operationalinsights/workspaces/workspace1"), -},new FirewallPolicyLogAnalyticsWorkspace() +}, new FirewallPolicyLogAnalyticsWorkspace { Region = "eastus", WorkspaceIdId = new ResourceIdentifier("/subscriptions/subid/resourcegroups/rg1/providers/microsoft.operationalinsights/workspaces/workspace2"), -} -}, +}}, DefaultWorkspaceIdId = new ResourceIdentifier("/subscriptions/subid/resourcegroups/rg1/providers/microsoft.operationalinsights/workspaces/defaultWorkspace"), }, }, - SnatPrivateRanges = -{ -"IANAPrivateRanges" -}, - DnsSettings = new DnsSettings() + SnatPrivateRanges = { "IANAPrivateRanges" }, + DnsSettings = new DnsSettings { - Servers = -{ -"30.3.4.5" -}, + Servers = { "30.3.4.5" }, EnableProxy = true, RequireProxyForNetworkRules = false, }, - IntrusionDetection = new FirewallPolicyIntrusionDetection() + IntrusionDetection = new FirewallPolicyIntrusionDetection { Mode = FirewallPolicyIntrusionDetectionStateType.Alert, - Configuration = new FirewallPolicyIntrusionDetectionConfiguration() + Configuration = new FirewallPolicyIntrusionDetectionConfiguration { - SignatureOverrides = -{ -new FirewallPolicyIntrusionDetectionSignatureSpecification() + SignatureOverrides = {new FirewallPolicyIntrusionDetectionSignatureSpecification { Id = "2525004", Mode = FirewallPolicyIntrusionDetectionStateType.Deny, -} -}, - BypassTrafficSettings = -{ -new FirewallPolicyIntrusionDetectionBypassTrafficSpecifications() +}}, + BypassTrafficSettings = {new FirewallPolicyIntrusionDetectionBypassTrafficSpecifications { Name = "bypassRule1", Description = "Rule 1", Protocol = FirewallPolicyIntrusionDetectionProtocol.TCP, -SourceAddresses = -{ -"1.2.3.4" -}, -DestinationAddresses = -{ -"5.6.7.8" -}, -DestinationPorts = -{ -"*" -}, -} -}, +SourceAddresses = {"1.2.3.4"}, +DestinationAddresses = {"5.6.7.8"}, +DestinationPorts = {"*"}, +}}, }, }, - TransportSecurityCertificateAuthority = new FirewallPolicyCertificateAuthority() + TransportSecurityCertificateAuthority = new FirewallPolicyCertificateAuthority { KeyVaultSecretId = "https://kv/secret", Name = "clientcert", @@ -246,7 +113,7 @@ public async Task CreateOrUpdate_CreateFirewallPolicy() SkuTier = FirewallPolicySkuTier.Premium, Tags = { -["key1"] = "value1", +["key1"] = "value1" }, }; ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, firewallPolicyName, data); @@ -285,7 +152,7 @@ public async Task CreateOrUpdate_CreateFirewallPolicyWithDifferentValues() string firewallPolicyName = "firewallPolicy"; FirewallPolicyData data = new FirewallPolicyData(new AzureLocation("West US")) { - StartupProbe = null, + StartupProbe = default, ReadinessProbe = new Probe(false) { InitialDelaySeconds = 30, @@ -293,88 +160,58 @@ public async Task CreateOrUpdate_CreateFirewallPolicyWithDifferentValues() FailureThreshold = 3, }, DesiredStatusCode = new DesiredStatusCode(600), - ThreatIntelWhitelist = new FirewallPolicyThreatIntelWhitelist() + ThreatIntelWhitelist = new FirewallPolicyThreatIntelWhitelist { - IpAddresses = -{ -IPAddress.Parse("20.3.4.5") -}, - Fqdns = -{ -"*.microsoft.com" -}, + IpAddresses = { IPAddress.Parse("20.3.4.5") }, + Fqdns = { "*.microsoft.com" }, }, - Insights = new FirewallPolicyInsights() + Insights = new FirewallPolicyInsights { IsEnabled = true, RetentionDays = 100, - LogAnalyticsResources = new FirewallPolicyLogAnalyticsResources() + LogAnalyticsResources = new FirewallPolicyLogAnalyticsResources { - Workspaces = -{ -new FirewallPolicyLogAnalyticsWorkspace() + Workspaces = {new FirewallPolicyLogAnalyticsWorkspace { Region = "westus", WorkspaceIdId = new ResourceIdentifier("/subscriptions/subid/resourcegroups/rg1/providers/microsoft.operationalinsights/workspaces/workspace1"), -},new FirewallPolicyLogAnalyticsWorkspace() +}, new FirewallPolicyLogAnalyticsWorkspace { Region = "eastus", WorkspaceIdId = new ResourceIdentifier("/subscriptions/subid/resourcegroups/rg1/providers/microsoft.operationalinsights/workspaces/workspace2"), -} -}, +}}, DefaultWorkspaceIdId = new ResourceIdentifier("/subscriptions/subid/resourcegroups/rg1/providers/microsoft.operationalinsights/workspaces/defaultWorkspace"), }, }, - SnatPrivateRanges = -{ -"IANAPrivateRanges" -}, - DnsSettings = new DnsSettings() + SnatPrivateRanges = { "IANAPrivateRanges" }, + DnsSettings = new DnsSettings { - Servers = -{ -"30.3.4.5" -}, + Servers = { "30.3.4.5" }, EnableProxy = true, RequireProxyForNetworkRules = false, }, - IntrusionDetection = new FirewallPolicyIntrusionDetection() + IntrusionDetection = new FirewallPolicyIntrusionDetection { Mode = FirewallPolicyIntrusionDetectionStateType.Alert, - Configuration = new FirewallPolicyIntrusionDetectionConfiguration() + Configuration = new FirewallPolicyIntrusionDetectionConfiguration { - SignatureOverrides = -{ -new FirewallPolicyIntrusionDetectionSignatureSpecification() + SignatureOverrides = {new FirewallPolicyIntrusionDetectionSignatureSpecification { Id = "2525004", Mode = FirewallPolicyIntrusionDetectionStateType.Deny, -} -}, - BypassTrafficSettings = -{ -new FirewallPolicyIntrusionDetectionBypassTrafficSpecifications() +}}, + BypassTrafficSettings = {new FirewallPolicyIntrusionDetectionBypassTrafficSpecifications { Name = "bypassRule1", Description = "Rule 1", Protocol = FirewallPolicyIntrusionDetectionProtocol.TCP, -SourceAddresses = -{ -"1.2.3.4" -}, -DestinationAddresses = -{ -"5.6.7.8" -}, -DestinationPorts = -{ -"*" -}, -} -}, +SourceAddresses = {"1.2.3.4"}, +DestinationAddresses = {"5.6.7.8"}, +DestinationPorts = {"*"}, +}}, }, }, - TransportSecurityCertificateAuthority = new FirewallPolicyCertificateAuthority() + TransportSecurityCertificateAuthority = new FirewallPolicyCertificateAuthority { KeyVaultSecretId = "https://kv/secret", Name = "clientcert", @@ -382,7 +219,7 @@ public async Task CreateOrUpdate_CreateFirewallPolicyWithDifferentValues() SkuTier = FirewallPolicySkuTier.Premium, Tags = { -["key1"] = "value1", +["key1"] = "value1" }, }; ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, firewallPolicyName, data); @@ -395,6 +232,39 @@ public async Task CreateOrUpdate_CreateFirewallPolicyWithDifferentValues() Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Get_GetFirewallPolicy() + { + // Generated from example definition: + // this example is just showing the usage of "FirewallPolicies_Get" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this ResourceGroupResource created on azure + // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource + string subscriptionId = "subid"; + string resourceGroupName = "rg1"; + ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); + ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); + + // get the collection of this FirewallPolicyResource + FirewallPolicyCollection collection = resourceGroupResource.GetFirewallPolicies(); + + // invoke the operation + string firewallPolicyName = "firewallPolicy"; + FirewallPolicyResource result = await collection.GetAsync(firewallPolicyName); + + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + FirewallPolicyData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + [Test] [Ignore("Only validating compilation of examples")] public async Task GetAll_ListAllFirewallPoliciesForAGivenResourceGroup() @@ -429,5 +299,75 @@ public async Task GetAll_ListAllFirewallPoliciesForAGivenResourceGroup() Console.WriteLine("Succeeded"); } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Exists_GetFirewallPolicy() + { + // Generated from example definition: + // this example is just showing the usage of "FirewallPolicies_Get" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this ResourceGroupResource created on azure + // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource + string subscriptionId = "subid"; + string resourceGroupName = "rg1"; + ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); + ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); + + // get the collection of this FirewallPolicyResource + FirewallPolicyCollection collection = resourceGroupResource.GetFirewallPolicies(); + + // invoke the operation + string firewallPolicyName = "firewallPolicy"; + bool result = await collection.ExistsAsync(firewallPolicyName); + + Console.WriteLine($"Succeeded: {result}"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetIfExists_GetFirewallPolicy() + { + // Generated from example definition: + // this example is just showing the usage of "FirewallPolicies_Get" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this ResourceGroupResource created on azure + // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource + string subscriptionId = "subid"; + string resourceGroupName = "rg1"; + ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); + ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); + + // get the collection of this FirewallPolicyResource + FirewallPolicyCollection collection = resourceGroupResource.GetFirewallPolicies(); + + // invoke the operation + string firewallPolicyName = "firewallPolicy"; + NullableResponse response = await collection.GetIfExistsAsync(firewallPolicyName); + FirewallPolicyResource result = response.HasValue ? response.Value : null; + + if (result == null) + { + Console.WriteLine("Succeeded with null as result"); + } + else + { + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + FirewallPolicyData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } } } diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyResource.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyResource.cs index 6da5d212edb..2f84bba2938 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyResource.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyResource.cs @@ -12,7 +12,6 @@ using Azure.Core; using Azure.Identity; using Azure.ResourceManager; -using Azure.ResourceManager.Resources; using MgmtMockAndSample.Models; using NUnit.Framework; @@ -22,10 +21,10 @@ public partial class Sample_FirewallPolicyResource { [Test] [Ignore("Only validating compilation of examples")] - public async Task Delete_DeleteFirewallPolicy() + public async Task Get_GetFirewallPolicy() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicies_Delete" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicies_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -41,17 +40,21 @@ public async Task Delete_DeleteFirewallPolicy() FirewallPolicyResource firewallPolicy = client.GetFirewallPolicyResource(firewallPolicyResourceId); // invoke the operation - await firewallPolicy.DeleteAsync(WaitUntil.Completed); + FirewallPolicyResource result = await firewallPolicy.GetAsync(); - Console.WriteLine("Succeeded"); + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + FirewallPolicyData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetFirewallPolicy() + public async Task Delete_DeleteFirewallPolicy() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicies_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicies_Delete" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -67,13 +70,9 @@ public async Task Get_GetFirewallPolicy() FirewallPolicyResource firewallPolicy = client.GetFirewallPolicyResource(firewallPolicyResourceId); // invoke the operation - FirewallPolicyResource result = await firewallPolicy.GetAsync(); + await firewallPolicy.DeleteAsync(WaitUntil.Completed); - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - FirewallPolicyData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + Console.WriteLine("Succeeded"); } [Test] @@ -99,7 +98,7 @@ public async Task Update_CreateFirewallPolicy() // invoke the operation FirewallPolicyData data = new FirewallPolicyData(new AzureLocation("West US")) { - StartupProbe = null, + StartupProbe = default, ReadinessProbe = new Probe(false) { InitialDelaySeconds = 30, @@ -107,88 +106,58 @@ public async Task Update_CreateFirewallPolicy() FailureThreshold = 3, }, DesiredStatusCode = DesiredStatusCode.TwoHundredTwo, - ThreatIntelWhitelist = new FirewallPolicyThreatIntelWhitelist() + ThreatIntelWhitelist = new FirewallPolicyThreatIntelWhitelist { - IpAddresses = -{ -IPAddress.Parse("20.3.4.5") -}, - Fqdns = -{ -"*.microsoft.com" -}, + IpAddresses = { IPAddress.Parse("20.3.4.5") }, + Fqdns = { "*.microsoft.com" }, }, - Insights = new FirewallPolicyInsights() + Insights = new FirewallPolicyInsights { IsEnabled = true, RetentionDays = 100, - LogAnalyticsResources = new FirewallPolicyLogAnalyticsResources() + LogAnalyticsResources = new FirewallPolicyLogAnalyticsResources { - Workspaces = -{ -new FirewallPolicyLogAnalyticsWorkspace() + Workspaces = {new FirewallPolicyLogAnalyticsWorkspace { Region = "westus", WorkspaceIdId = new ResourceIdentifier("/subscriptions/subid/resourcegroups/rg1/providers/microsoft.operationalinsights/workspaces/workspace1"), -},new FirewallPolicyLogAnalyticsWorkspace() +}, new FirewallPolicyLogAnalyticsWorkspace { Region = "eastus", WorkspaceIdId = new ResourceIdentifier("/subscriptions/subid/resourcegroups/rg1/providers/microsoft.operationalinsights/workspaces/workspace2"), -} -}, +}}, DefaultWorkspaceIdId = new ResourceIdentifier("/subscriptions/subid/resourcegroups/rg1/providers/microsoft.operationalinsights/workspaces/defaultWorkspace"), }, }, - SnatPrivateRanges = -{ -"IANAPrivateRanges" -}, - DnsSettings = new DnsSettings() + SnatPrivateRanges = { "IANAPrivateRanges" }, + DnsSettings = new DnsSettings { - Servers = -{ -"30.3.4.5" -}, + Servers = { "30.3.4.5" }, EnableProxy = true, RequireProxyForNetworkRules = false, }, - IntrusionDetection = new FirewallPolicyIntrusionDetection() + IntrusionDetection = new FirewallPolicyIntrusionDetection { Mode = FirewallPolicyIntrusionDetectionStateType.Alert, - Configuration = new FirewallPolicyIntrusionDetectionConfiguration() + Configuration = new FirewallPolicyIntrusionDetectionConfiguration { - SignatureOverrides = -{ -new FirewallPolicyIntrusionDetectionSignatureSpecification() + SignatureOverrides = {new FirewallPolicyIntrusionDetectionSignatureSpecification { Id = "2525004", Mode = FirewallPolicyIntrusionDetectionStateType.Deny, -} -}, - BypassTrafficSettings = -{ -new FirewallPolicyIntrusionDetectionBypassTrafficSpecifications() +}}, + BypassTrafficSettings = {new FirewallPolicyIntrusionDetectionBypassTrafficSpecifications { Name = "bypassRule1", Description = "Rule 1", Protocol = FirewallPolicyIntrusionDetectionProtocol.TCP, -SourceAddresses = -{ -"1.2.3.4" -}, -DestinationAddresses = -{ -"5.6.7.8" -}, -DestinationPorts = -{ -"*" -}, -} -}, +SourceAddresses = {"1.2.3.4"}, +DestinationAddresses = {"5.6.7.8"}, +DestinationPorts = {"*"}, +}}, }, }, - TransportSecurityCertificateAuthority = new FirewallPolicyCertificateAuthority() + TransportSecurityCertificateAuthority = new FirewallPolicyCertificateAuthority { KeyVaultSecretId = "https://kv/secret", Name = "clientcert", @@ -196,7 +165,7 @@ public async Task Update_CreateFirewallPolicy() SkuTier = FirewallPolicySkuTier.Premium, Tags = { -["key1"] = "value1", +["key1"] = "value1" }, }; ArmOperation lro = await firewallPolicy.UpdateAsync(WaitUntil.Completed, data); @@ -232,7 +201,7 @@ public async Task Update_CreateFirewallPolicyWithDifferentValues() // invoke the operation FirewallPolicyData data = new FirewallPolicyData(new AzureLocation("West US")) { - StartupProbe = null, + StartupProbe = default, ReadinessProbe = new Probe(false) { InitialDelaySeconds = 30, @@ -240,88 +209,58 @@ public async Task Update_CreateFirewallPolicyWithDifferentValues() FailureThreshold = 3, }, DesiredStatusCode = new DesiredStatusCode(600), - ThreatIntelWhitelist = new FirewallPolicyThreatIntelWhitelist() + ThreatIntelWhitelist = new FirewallPolicyThreatIntelWhitelist { - IpAddresses = -{ -IPAddress.Parse("20.3.4.5") -}, - Fqdns = -{ -"*.microsoft.com" -}, + IpAddresses = { IPAddress.Parse("20.3.4.5") }, + Fqdns = { "*.microsoft.com" }, }, - Insights = new FirewallPolicyInsights() + Insights = new FirewallPolicyInsights { IsEnabled = true, RetentionDays = 100, - LogAnalyticsResources = new FirewallPolicyLogAnalyticsResources() + LogAnalyticsResources = new FirewallPolicyLogAnalyticsResources { - Workspaces = -{ -new FirewallPolicyLogAnalyticsWorkspace() + Workspaces = {new FirewallPolicyLogAnalyticsWorkspace { Region = "westus", WorkspaceIdId = new ResourceIdentifier("/subscriptions/subid/resourcegroups/rg1/providers/microsoft.operationalinsights/workspaces/workspace1"), -},new FirewallPolicyLogAnalyticsWorkspace() +}, new FirewallPolicyLogAnalyticsWorkspace { Region = "eastus", WorkspaceIdId = new ResourceIdentifier("/subscriptions/subid/resourcegroups/rg1/providers/microsoft.operationalinsights/workspaces/workspace2"), -} -}, +}}, DefaultWorkspaceIdId = new ResourceIdentifier("/subscriptions/subid/resourcegroups/rg1/providers/microsoft.operationalinsights/workspaces/defaultWorkspace"), }, }, - SnatPrivateRanges = -{ -"IANAPrivateRanges" -}, - DnsSettings = new DnsSettings() + SnatPrivateRanges = { "IANAPrivateRanges" }, + DnsSettings = new DnsSettings { - Servers = -{ -"30.3.4.5" -}, + Servers = { "30.3.4.5" }, EnableProxy = true, RequireProxyForNetworkRules = false, }, - IntrusionDetection = new FirewallPolicyIntrusionDetection() + IntrusionDetection = new FirewallPolicyIntrusionDetection { Mode = FirewallPolicyIntrusionDetectionStateType.Alert, - Configuration = new FirewallPolicyIntrusionDetectionConfiguration() + Configuration = new FirewallPolicyIntrusionDetectionConfiguration { - SignatureOverrides = -{ -new FirewallPolicyIntrusionDetectionSignatureSpecification() + SignatureOverrides = {new FirewallPolicyIntrusionDetectionSignatureSpecification { Id = "2525004", Mode = FirewallPolicyIntrusionDetectionStateType.Deny, -} -}, - BypassTrafficSettings = -{ -new FirewallPolicyIntrusionDetectionBypassTrafficSpecifications() +}}, + BypassTrafficSettings = {new FirewallPolicyIntrusionDetectionBypassTrafficSpecifications { Name = "bypassRule1", Description = "Rule 1", Protocol = FirewallPolicyIntrusionDetectionProtocol.TCP, -SourceAddresses = -{ -"1.2.3.4" -}, -DestinationAddresses = -{ -"5.6.7.8" -}, -DestinationPorts = -{ -"*" -}, -} -}, +SourceAddresses = {"1.2.3.4"}, +DestinationAddresses = {"5.6.7.8"}, +DestinationPorts = {"*"}, +}}, }, }, - TransportSecurityCertificateAuthority = new FirewallPolicyCertificateAuthority() + TransportSecurityCertificateAuthority = new FirewallPolicyCertificateAuthority { KeyVaultSecretId = "https://kv/secret", Name = "clientcert", @@ -329,7 +268,7 @@ public async Task Update_CreateFirewallPolicyWithDifferentValues() SkuTier = FirewallPolicySkuTier.Premium, Tags = { -["key1"] = "value1", +["key1"] = "value1" }, }; ArmOperation lro = await firewallPolicy.UpdateAsync(WaitUntil.Completed, data); @@ -341,36 +280,5 @@ public async Task Update_CreateFirewallPolicyWithDifferentValues() // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task GetFirewallPolicies_ListAllFirewallPoliciesForAGivenSubscription() - { - // Generated from example definition: - // this example is just showing the usage of "FirewallPolicies_ListAll" operation, for the dependent resources, they will have to be created separately. - - // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line - TokenCredential cred = new DefaultAzureCredential(); - // authenticate your client - ArmClient client = new ArmClient(cred); - - // this example assumes you already have this SubscriptionResource created on azure - // for more information of creating SubscriptionResource, please refer to the document of SubscriptionResource - string subscriptionId = "subid"; - ResourceIdentifier subscriptionResourceId = SubscriptionResource.CreateResourceIdentifier(subscriptionId); - SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); - - // invoke the operation and iterate over the result - await foreach (FirewallPolicyResource item in subscriptionResource.GetFirewallPoliciesAsync()) - { - // the variable item is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - FirewallPolicyData resourceData = item.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } - - Console.WriteLine("Succeeded"); - } } } diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyRuleCollectionGroupCollection.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyRuleCollectionGroupCollection.cs index e83822bad4e..b7df2d779e4 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyRuleCollectionGroupCollection.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyRuleCollectionGroupCollection.cs @@ -20,10 +20,10 @@ public partial class Sample_FirewallPolicyRuleCollectionGroupCollection { [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetFirewallPolicyNatRuleCollectionGroup() + public async Task CreateOrUpdate_CreateFirewallPolicyNatRuleCollectionGroup() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -43,7 +43,29 @@ public async Task Get_GetFirewallPolicyNatRuleCollectionGroup() // invoke the operation string ruleCollectionGroupName = "ruleCollectionGroup1"; - FirewallPolicyRuleCollectionGroupResource result = await collection.GetAsync(ruleCollectionGroupName); + FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData + { + Priority = 100, + RuleCollections = {new FirewallPolicyNatRuleCollection +{ +ActionType = FirewallPolicyNatRuleCollectionActionType.Dnat, +Rules = {new NatRule +{ +IpProtocols = {FirewallPolicyRuleNetworkProtocol.TCP, FirewallPolicyRuleNetworkProtocol.UDP}, +SourceAddresses = {"2.2.2.2"}, +DestinationAddresses = {"152.23.32.23"}, +DestinationPorts = {"8080"}, +TranslatedPort = "8080", +SourceIpGroups = {}, +TranslatedFqdn = "internalhttp.server.net", +Name = "nat-rule1", +}}, +Name = "Example-Nat-Rule-Collection", +Priority = 100, +}}, + }; + ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, ruleCollectionGroupName, data); + FirewallPolicyRuleCollectionGroupResource result = lro.Value; // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance @@ -54,10 +76,10 @@ public async Task Get_GetFirewallPolicyNatRuleCollectionGroup() [Test] [Ignore("Only validating compilation of examples")] - public async Task Exists_GetFirewallPolicyNatRuleCollectionGroup() + public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroup() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -77,17 +99,40 @@ public async Task Exists_GetFirewallPolicyNatRuleCollectionGroup() // invoke the operation string ruleCollectionGroupName = "ruleCollectionGroup1"; - bool result = await collection.ExistsAsync(ruleCollectionGroupName); + FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData + { + Priority = 100, + RuleCollections = {new FirewallPolicyFilterRuleCollection +{ +ActionType = FirewallPolicyFilterRuleCollectionActionType.Deny, +Rules = {new NetworkRule +{ +IpProtocols = {FirewallPolicyRuleNetworkProtocol.TCP}, +SourceAddresses = {"10.1.25.0/24"}, +DestinationAddresses = {"*"}, +DestinationPorts = {"*"}, +Name = "network-rule1", +}}, +Name = "Example-Filter-Rule-Collection", +Priority = 100, +}}, + }; + ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, ruleCollectionGroupName, data); + FirewallPolicyRuleCollectionGroupResource result = lro.Value; - Console.WriteLine($"Succeeded: {result}"); + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + FirewallPolicyRuleCollectionGroupData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetIfExists_GetFirewallPolicyNatRuleCollectionGroup() + public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroupWithAllDefaultValues() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -96,7 +141,7 @@ public async Task GetIfExists_GetFirewallPolicyNatRuleCollectionGroup() // this example assumes you already have this FirewallPolicyResource created on azure // for more information of creating FirewallPolicyResource, please refer to the document of FirewallPolicyResource - string subscriptionId = "subid"; + string subscriptionId = "e747cc13-97d4-4a79-b463-42d7f4e558f2"; string resourceGroupName = "rg1"; string firewallPolicyName = "firewallPolicy"; ResourceIdentifier firewallPolicyResourceId = FirewallPolicyResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, firewallPolicyName); @@ -107,29 +152,23 @@ public async Task GetIfExists_GetFirewallPolicyNatRuleCollectionGroup() // invoke the operation string ruleCollectionGroupName = "ruleCollectionGroup1"; - NullableResponse response = await collection.GetIfExistsAsync(ruleCollectionGroupName); - FirewallPolicyRuleCollectionGroupResource result = response.HasValue ? response.Value : null; + FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData(); + ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, ruleCollectionGroupName, data); + FirewallPolicyRuleCollectionGroupResource result = lro.Value; - if (result == null) - { - Console.WriteLine("Succeeded with null as result"); - } - else - { - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - FirewallPolicyRuleCollectionGroupData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + FirewallPolicyRuleCollectionGroupData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetFirewallPolicyRuleCollectionGroup() + public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroupWithIpGroups() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -149,7 +188,25 @@ public async Task Get_GetFirewallPolicyRuleCollectionGroup() // invoke the operation string ruleCollectionGroupName = "ruleCollectionGroup1"; - FirewallPolicyRuleCollectionGroupResource result = await collection.GetAsync(ruleCollectionGroupName); + FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData + { + Priority = 110, + RuleCollections = {new FirewallPolicyFilterRuleCollection +{ +ActionType = FirewallPolicyFilterRuleCollectionActionType.Deny, +Rules = {new NetworkRule +{ +IpProtocols = {FirewallPolicyRuleNetworkProtocol.TCP}, +DestinationPorts = {"*"}, +SourceIpGroups = {"/subscriptions/subid/providers/Microsoft.Network/resourceGroup/rg1/ipGroups/ipGroups1"}, +DestinationIpGroups = {"/subscriptions/subid/providers/Microsoft.Network/resourceGroup/rg1/ipGroups/ipGroups2"}, +Name = "network-1", +}}, +Name = "Example-Filter-Rule-Collection", +}}, + }; + ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, ruleCollectionGroupName, data); + FirewallPolicyRuleCollectionGroupResource result = lro.Value; // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance @@ -160,10 +217,10 @@ public async Task Get_GetFirewallPolicyRuleCollectionGroup() [Test] [Ignore("Only validating compilation of examples")] - public async Task Exists_GetFirewallPolicyRuleCollectionGroup() + public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroupWithWebCategories() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -172,7 +229,7 @@ public async Task Exists_GetFirewallPolicyRuleCollectionGroup() // this example assumes you already have this FirewallPolicyResource created on azure // for more information of creating FirewallPolicyResource, please refer to the document of FirewallPolicyResource - string subscriptionId = "subid"; + string subscriptionId = "e747cc13-97d4-4a79-b463-42d7f4e558f2"; string resourceGroupName = "rg1"; string firewallPolicyName = "firewallPolicy"; ResourceIdentifier firewallPolicyResourceId = FirewallPolicyResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, firewallPolicyName); @@ -183,14 +240,40 @@ public async Task Exists_GetFirewallPolicyRuleCollectionGroup() // invoke the operation string ruleCollectionGroupName = "ruleCollectionGroup1"; - bool result = await collection.ExistsAsync(ruleCollectionGroupName); + FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData + { + Priority = 110, + RuleCollections = {new FirewallPolicyFilterRuleCollection +{ +ActionType = FirewallPolicyFilterRuleCollectionActionType.Deny, +Rules = {new ApplicationRule +{ +SourceAddresses = {"216.58.216.164", "10.0.0.0/24"}, +Protocols = {new FirewallPolicyRuleApplicationProtocol +{ +ProtocolType = FirewallPolicyRuleApplicationProtocolType.Https, +Port = 443, +}}, +WebCategories = {"Hacking"}, +Name = "rule1", +Description = "Deny inbound rule", +}}, +Name = "Example-Filter-Rule-Collection", +}}, + }; + ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, ruleCollectionGroupName, data); + FirewallPolicyRuleCollectionGroupResource result = lro.Value; - Console.WriteLine($"Succeeded: {result}"); + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + FirewallPolicyRuleCollectionGroupData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetIfExists_GetFirewallPolicyRuleCollectionGroup() + public async Task Get_GetFirewallPolicyNatRuleCollectionGroup() { // Generated from example definition: // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. @@ -213,26 +296,18 @@ public async Task GetIfExists_GetFirewallPolicyRuleCollectionGroup() // invoke the operation string ruleCollectionGroupName = "ruleCollectionGroup1"; - NullableResponse response = await collection.GetIfExistsAsync(ruleCollectionGroupName); - FirewallPolicyRuleCollectionGroupResource result = response.HasValue ? response.Value : null; + FirewallPolicyRuleCollectionGroupResource result = await collection.GetAsync(ruleCollectionGroupName); - if (result == null) - { - Console.WriteLine("Succeeded with null as result"); - } - else - { - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - FirewallPolicyRuleCollectionGroupData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + FirewallPolicyRuleCollectionGroupData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetFirewallPolicyRuleCollectionGroupWithIpGroups() + public async Task Get_GetFirewallPolicyRuleCollectionGroup() { // Generated from example definition: // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. @@ -254,7 +329,7 @@ public async Task Get_GetFirewallPolicyRuleCollectionGroupWithIpGroups() FirewallPolicyRuleCollectionGroupCollection collection = firewallPolicy.GetFirewallPolicyRuleCollectionGroups(); // invoke the operation - string ruleCollectionGroupName = "ruleGroup1"; + string ruleCollectionGroupName = "ruleCollectionGroup1"; FirewallPolicyRuleCollectionGroupResource result = await collection.GetAsync(ruleCollectionGroupName); // the variable result is a resource, you could call other operations on this instance as well @@ -266,7 +341,7 @@ public async Task Get_GetFirewallPolicyRuleCollectionGroupWithIpGroups() [Test] [Ignore("Only validating compilation of examples")] - public async Task Exists_GetFirewallPolicyRuleCollectionGroupWithIpGroups() + public async Task Get_GetFirewallPolicyRuleCollectionGroupWithIpGroups() { // Generated from example definition: // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. @@ -289,14 +364,18 @@ public async Task Exists_GetFirewallPolicyRuleCollectionGroupWithIpGroups() // invoke the operation string ruleCollectionGroupName = "ruleGroup1"; - bool result = await collection.ExistsAsync(ruleCollectionGroupName); + FirewallPolicyRuleCollectionGroupResource result = await collection.GetAsync(ruleCollectionGroupName); - Console.WriteLine($"Succeeded: {result}"); + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + FirewallPolicyRuleCollectionGroupData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetIfExists_GetFirewallPolicyRuleCollectionGroupWithIpGroups() + public async Task Get_GetFirewallPolicyRuleCollectionGroupWithWebCategories() { // Generated from example definition: // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. @@ -308,7 +387,7 @@ public async Task GetIfExists_GetFirewallPolicyRuleCollectionGroupWithIpGroups() // this example assumes you already have this FirewallPolicyResource created on azure // for more information of creating FirewallPolicyResource, please refer to the document of FirewallPolicyResource - string subscriptionId = "subid"; + string subscriptionId = "e747cc13-97d4-4a79-b463-42d7f4e558f2"; string resourceGroupName = "rg1"; string firewallPolicyName = "firewallPolicy"; ResourceIdentifier firewallPolicyResourceId = FirewallPolicyResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, firewallPolicyName); @@ -318,30 +397,22 @@ public async Task GetIfExists_GetFirewallPolicyRuleCollectionGroupWithIpGroups() FirewallPolicyRuleCollectionGroupCollection collection = firewallPolicy.GetFirewallPolicyRuleCollectionGroups(); // invoke the operation - string ruleCollectionGroupName = "ruleGroup1"; - NullableResponse response = await collection.GetIfExistsAsync(ruleCollectionGroupName); - FirewallPolicyRuleCollectionGroupResource result = response.HasValue ? response.Value : null; + string ruleCollectionGroupName = "ruleCollectionGroup1"; + FirewallPolicyRuleCollectionGroupResource result = await collection.GetAsync(ruleCollectionGroupName); - if (result == null) - { - Console.WriteLine("Succeeded with null as result"); - } - else - { - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - FirewallPolicyRuleCollectionGroupData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + FirewallPolicyRuleCollectionGroupData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetFirewallPolicyRuleCollectionGroupWithWebCategories() + public async Task GetAll_ListAllFirewallPolicyRuleCollectionGroupWithWebCategories() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_List" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -359,23 +430,25 @@ public async Task Get_GetFirewallPolicyRuleCollectionGroupWithWebCategories() // get the collection of this FirewallPolicyRuleCollectionGroupResource FirewallPolicyRuleCollectionGroupCollection collection = firewallPolicy.GetFirewallPolicyRuleCollectionGroups(); - // invoke the operation - string ruleCollectionGroupName = "ruleCollectionGroup1"; - FirewallPolicyRuleCollectionGroupResource result = await collection.GetAsync(ruleCollectionGroupName); + // invoke the operation and iterate over the result + await foreach (FirewallPolicyRuleCollectionGroupResource item in collection.GetAllAsync()) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + FirewallPolicyRuleCollectionGroupData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - FirewallPolicyRuleCollectionGroupData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Exists_GetFirewallPolicyRuleCollectionGroupWithWebCategories() + public async Task GetAll_ListAllFirewallPolicyRuleCollectionGroupsForAGivenFirewallPolicy() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_List" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -384,7 +457,7 @@ public async Task Exists_GetFirewallPolicyRuleCollectionGroupWithWebCategories() // this example assumes you already have this FirewallPolicyResource created on azure // for more information of creating FirewallPolicyResource, please refer to the document of FirewallPolicyResource - string subscriptionId = "e747cc13-97d4-4a79-b463-42d7f4e558f2"; + string subscriptionId = "subid"; string resourceGroupName = "rg1"; string firewallPolicyName = "firewallPolicy"; ResourceIdentifier firewallPolicyResourceId = FirewallPolicyResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, firewallPolicyName); @@ -393,19 +466,25 @@ public async Task Exists_GetFirewallPolicyRuleCollectionGroupWithWebCategories() // get the collection of this FirewallPolicyRuleCollectionGroupResource FirewallPolicyRuleCollectionGroupCollection collection = firewallPolicy.GetFirewallPolicyRuleCollectionGroups(); - // invoke the operation - string ruleCollectionGroupName = "ruleCollectionGroup1"; - bool result = await collection.ExistsAsync(ruleCollectionGroupName); + // invoke the operation and iterate over the result + await foreach (FirewallPolicyRuleCollectionGroupResource item in collection.GetAllAsync()) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + FirewallPolicyRuleCollectionGroupData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } - Console.WriteLine($"Succeeded: {result}"); + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetIfExists_GetFirewallPolicyRuleCollectionGroupWithWebCategories() + public async Task GetAll_ListAllFirewallPolicyRuleCollectionGroupsWithIpGroupsForAGivenFirewallPolicy() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_List" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -414,7 +493,7 @@ public async Task GetIfExists_GetFirewallPolicyRuleCollectionGroupWithWebCategor // this example assumes you already have this FirewallPolicyResource created on azure // for more information of creating FirewallPolicyResource, please refer to the document of FirewallPolicyResource - string subscriptionId = "e747cc13-97d4-4a79-b463-42d7f4e558f2"; + string subscriptionId = "subid"; string resourceGroupName = "rg1"; string firewallPolicyName = "firewallPolicy"; ResourceIdentifier firewallPolicyResourceId = FirewallPolicyResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, firewallPolicyName); @@ -423,31 +502,25 @@ public async Task GetIfExists_GetFirewallPolicyRuleCollectionGroupWithWebCategor // get the collection of this FirewallPolicyRuleCollectionGroupResource FirewallPolicyRuleCollectionGroupCollection collection = firewallPolicy.GetFirewallPolicyRuleCollectionGroups(); - // invoke the operation - string ruleCollectionGroupName = "ruleCollectionGroup1"; - NullableResponse response = await collection.GetIfExistsAsync(ruleCollectionGroupName); - FirewallPolicyRuleCollectionGroupResource result = response.HasValue ? response.Value : null; - - if (result == null) - { - Console.WriteLine("Succeeded with null as result"); - } - else + // invoke the operation and iterate over the result + await foreach (FirewallPolicyRuleCollectionGroupResource item in collection.GetAllAsync()) { - // the variable result is a resource, you could call other operations on this instance as well + // the variable item is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - FirewallPolicyRuleCollectionGroupData resourceData = result.Data; + FirewallPolicyRuleCollectionGroupData resourceData = item.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } + + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task CreateOrUpdate_CreateFirewallPolicyNatRuleCollectionGroup() + public async Task Exists_GetFirewallPolicyNatRuleCollectionGroup() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -467,63 +540,17 @@ public async Task CreateOrUpdate_CreateFirewallPolicyNatRuleCollectionGroup() // invoke the operation string ruleCollectionGroupName = "ruleCollectionGroup1"; - FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData() - { - Priority = 100, - RuleCollections = -{ -new FirewallPolicyNatRuleCollection() -{ -ActionType = FirewallPolicyNatRuleCollectionActionType.Dnat, -Rules = -{ -new NatRule() -{ -IpProtocols = -{ -FirewallPolicyRuleNetworkProtocol.TCP,FirewallPolicyRuleNetworkProtocol.UDP -}, -SourceAddresses = -{ -"2.2.2.2" -}, -DestinationAddresses = -{ -"152.23.32.23" -}, -DestinationPorts = -{ -"8080" -}, -TranslatedPort = "8080", -SourceIpGroups = -{ -}, -TranslatedFqdn = "internalhttp.server.net", -Name = "nat-rule1", -} -}, -Name = "Example-Nat-Rule-Collection", -Priority = 100, -} -}, - }; - ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, ruleCollectionGroupName, data); - FirewallPolicyRuleCollectionGroupResource result = lro.Value; + bool result = await collection.ExistsAsync(ruleCollectionGroupName); - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - FirewallPolicyRuleCollectionGroupData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + Console.WriteLine($"Succeeded: {result}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroup() + public async Task Exists_GetFirewallPolicyRuleCollectionGroup() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -543,58 +570,17 @@ public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroup() // invoke the operation string ruleCollectionGroupName = "ruleCollectionGroup1"; - FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData() - { - Priority = 100, - RuleCollections = -{ -new FirewallPolicyFilterRuleCollection() -{ -ActionType = FirewallPolicyFilterRuleCollectionActionType.Deny, -Rules = -{ -new NetworkRule() -{ -IpProtocols = -{ -FirewallPolicyRuleNetworkProtocol.TCP -}, -SourceAddresses = -{ -"10.1.25.0/24" -}, -DestinationAddresses = -{ -"*" -}, -DestinationPorts = -{ -"*" -}, -Name = "network-rule1", -} -}, -Name = "Example-Filter-Rule-Collection", -Priority = 100, -} -}, - }; - ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, ruleCollectionGroupName, data); - FirewallPolicyRuleCollectionGroupResource result = lro.Value; + bool result = await collection.ExistsAsync(ruleCollectionGroupName); - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - FirewallPolicyRuleCollectionGroupData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + Console.WriteLine($"Succeeded: {result}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroupWithAllDefaultValues() + public async Task Exists_GetFirewallPolicyRuleCollectionGroupWithIpGroups() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -603,7 +589,7 @@ public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroupWithAllD // this example assumes you already have this FirewallPolicyResource created on azure // for more information of creating FirewallPolicyResource, please refer to the document of FirewallPolicyResource - string subscriptionId = "e747cc13-97d4-4a79-b463-42d7f4e558f2"; + string subscriptionId = "subid"; string resourceGroupName = "rg1"; string firewallPolicyName = "firewallPolicy"; ResourceIdentifier firewallPolicyResourceId = FirewallPolicyResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, firewallPolicyName); @@ -613,24 +599,18 @@ public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroupWithAllD FirewallPolicyRuleCollectionGroupCollection collection = firewallPolicy.GetFirewallPolicyRuleCollectionGroups(); // invoke the operation - string ruleCollectionGroupName = "ruleCollectionGroup1"; - FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData(); - ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, ruleCollectionGroupName, data); - FirewallPolicyRuleCollectionGroupResource result = lro.Value; + string ruleCollectionGroupName = "ruleGroup1"; + bool result = await collection.ExistsAsync(ruleCollectionGroupName); - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - FirewallPolicyRuleCollectionGroupData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + Console.WriteLine($"Succeeded: {result}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroupWithIpGroups() + public async Task Exists_GetFirewallPolicyRuleCollectionGroupWithWebCategories() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -639,7 +619,7 @@ public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroupWithIpGr // this example assumes you already have this FirewallPolicyResource created on azure // for more information of creating FirewallPolicyResource, please refer to the document of FirewallPolicyResource - string subscriptionId = "subid"; + string subscriptionId = "e747cc13-97d4-4a79-b463-42d7f4e558f2"; string resourceGroupName = "rg1"; string firewallPolicyName = "firewallPolicy"; ResourceIdentifier firewallPolicyResourceId = FirewallPolicyResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, firewallPolicyName); @@ -650,57 +630,17 @@ public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroupWithIpGr // invoke the operation string ruleCollectionGroupName = "ruleCollectionGroup1"; - FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData() - { - Priority = 110, - RuleCollections = -{ -new FirewallPolicyFilterRuleCollection() -{ -ActionType = FirewallPolicyFilterRuleCollectionActionType.Deny, -Rules = -{ -new NetworkRule() -{ -IpProtocols = -{ -FirewallPolicyRuleNetworkProtocol.TCP -}, -DestinationPorts = -{ -"*" -}, -SourceIpGroups = -{ -"/subscriptions/subid/providers/Microsoft.Network/resourceGroup/rg1/ipGroups/ipGroups1" -}, -DestinationIpGroups = -{ -"/subscriptions/subid/providers/Microsoft.Network/resourceGroup/rg1/ipGroups/ipGroups2" -}, -Name = "network-1", -} -}, -Name = "Example-Filter-Rule-Collection", -} -}, - }; - ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, ruleCollectionGroupName, data); - FirewallPolicyRuleCollectionGroupResource result = lro.Value; + bool result = await collection.ExistsAsync(ruleCollectionGroupName); - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - FirewallPolicyRuleCollectionGroupData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + Console.WriteLine($"Succeeded: {result}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroupWithWebCategories() + public async Task GetIfExists_GetFirewallPolicyNatRuleCollectionGroup() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -709,7 +649,7 @@ public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroupWithWebC // this example assumes you already have this FirewallPolicyResource created on azure // for more information of creating FirewallPolicyResource, please refer to the document of FirewallPolicyResource - string subscriptionId = "e747cc13-97d4-4a79-b463-42d7f4e558f2"; + string subscriptionId = "subid"; string resourceGroupName = "rg1"; string firewallPolicyName = "firewallPolicy"; ResourceIdentifier firewallPolicyResourceId = FirewallPolicyResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, firewallPolicyName); @@ -720,58 +660,29 @@ public async Task CreateOrUpdate_CreateFirewallPolicyRuleCollectionGroupWithWebC // invoke the operation string ruleCollectionGroupName = "ruleCollectionGroup1"; - FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData() - { - Priority = 110, - RuleCollections = -{ -new FirewallPolicyFilterRuleCollection() -{ -ActionType = FirewallPolicyFilterRuleCollectionActionType.Deny, -Rules = -{ -new ApplicationRule() -{ -SourceAddresses = -{ -"216.58.216.164","10.0.0.0/24" -}, -Protocols = -{ -new FirewallPolicyRuleApplicationProtocol() -{ -ProtocolType = FirewallPolicyRuleApplicationProtocolType.Https, -Port = 443, -} -}, -WebCategories = -{ -"Hacking" -}, -Name = "rule1", -Description = "Deny inbound rule", -} -}, -Name = "Example-Filter-Rule-Collection", -} -}, - }; - ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, ruleCollectionGroupName, data); - FirewallPolicyRuleCollectionGroupResource result = lro.Value; + NullableResponse response = await collection.GetIfExistsAsync(ruleCollectionGroupName); + FirewallPolicyRuleCollectionGroupResource result = response.HasValue ? response.Value : null; - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - FirewallPolicyRuleCollectionGroupData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + if (result == null) + { + Console.WriteLine("Succeeded with null as result"); + } + else + { + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + FirewallPolicyRuleCollectionGroupData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetAll_ListAllFirewallPolicyRuleCollectionGroupWithWebCategories() + public async Task GetIfExists_GetFirewallPolicyRuleCollectionGroup() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_List" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -780,7 +691,7 @@ public async Task GetAll_ListAllFirewallPolicyRuleCollectionGroupWithWebCategori // this example assumes you already have this FirewallPolicyResource created on azure // for more information of creating FirewallPolicyResource, please refer to the document of FirewallPolicyResource - string subscriptionId = "e747cc13-97d4-4a79-b463-42d7f4e558f2"; + string subscriptionId = "subid"; string resourceGroupName = "rg1"; string firewallPolicyName = "firewallPolicy"; ResourceIdentifier firewallPolicyResourceId = FirewallPolicyResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, firewallPolicyName); @@ -789,25 +700,31 @@ public async Task GetAll_ListAllFirewallPolicyRuleCollectionGroupWithWebCategori // get the collection of this FirewallPolicyRuleCollectionGroupResource FirewallPolicyRuleCollectionGroupCollection collection = firewallPolicy.GetFirewallPolicyRuleCollectionGroups(); - // invoke the operation and iterate over the result - await foreach (FirewallPolicyRuleCollectionGroupResource item in collection.GetAllAsync()) + // invoke the operation + string ruleCollectionGroupName = "ruleCollectionGroup1"; + NullableResponse response = await collection.GetIfExistsAsync(ruleCollectionGroupName); + FirewallPolicyRuleCollectionGroupResource result = response.HasValue ? response.Value : null; + + if (result == null) { - // the variable item is a resource, you could call other operations on this instance as well + Console.WriteLine("Succeeded with null as result"); + } + else + { + // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - FirewallPolicyRuleCollectionGroupData resourceData = item.Data; + FirewallPolicyRuleCollectionGroupData resourceData = result.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } - - Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetAll_ListAllFirewallPolicyRuleCollectionGroupsForAGivenFirewallPolicy() + public async Task GetIfExists_GetFirewallPolicyRuleCollectionGroupWithIpGroups() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_List" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -825,25 +742,31 @@ public async Task GetAll_ListAllFirewallPolicyRuleCollectionGroupsForAGivenFirew // get the collection of this FirewallPolicyRuleCollectionGroupResource FirewallPolicyRuleCollectionGroupCollection collection = firewallPolicy.GetFirewallPolicyRuleCollectionGroups(); - // invoke the operation and iterate over the result - await foreach (FirewallPolicyRuleCollectionGroupResource item in collection.GetAllAsync()) + // invoke the operation + string ruleCollectionGroupName = "ruleGroup1"; + NullableResponse response = await collection.GetIfExistsAsync(ruleCollectionGroupName); + FirewallPolicyRuleCollectionGroupResource result = response.HasValue ? response.Value : null; + + if (result == null) { - // the variable item is a resource, you could call other operations on this instance as well + Console.WriteLine("Succeeded with null as result"); + } + else + { + // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - FirewallPolicyRuleCollectionGroupData resourceData = item.Data; + FirewallPolicyRuleCollectionGroupData resourceData = result.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } - - Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetAll_ListAllFirewallPolicyRuleCollectionGroupsWithIpGroupsForAGivenFirewallPolicy() + public async Task GetIfExists_GetFirewallPolicyRuleCollectionGroupWithWebCategories() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_List" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -852,7 +775,7 @@ public async Task GetAll_ListAllFirewallPolicyRuleCollectionGroupsWithIpGroupsFo // this example assumes you already have this FirewallPolicyResource created on azure // for more information of creating FirewallPolicyResource, please refer to the document of FirewallPolicyResource - string subscriptionId = "subid"; + string subscriptionId = "e747cc13-97d4-4a79-b463-42d7f4e558f2"; string resourceGroupName = "rg1"; string firewallPolicyName = "firewallPolicy"; ResourceIdentifier firewallPolicyResourceId = FirewallPolicyResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, firewallPolicyName); @@ -861,17 +784,23 @@ public async Task GetAll_ListAllFirewallPolicyRuleCollectionGroupsWithIpGroupsFo // get the collection of this FirewallPolicyRuleCollectionGroupResource FirewallPolicyRuleCollectionGroupCollection collection = firewallPolicy.GetFirewallPolicyRuleCollectionGroups(); - // invoke the operation and iterate over the result - await foreach (FirewallPolicyRuleCollectionGroupResource item in collection.GetAllAsync()) + // invoke the operation + string ruleCollectionGroupName = "ruleCollectionGroup1"; + NullableResponse response = await collection.GetIfExistsAsync(ruleCollectionGroupName); + FirewallPolicyRuleCollectionGroupResource result = response.HasValue ? response.Value : null; + + if (result == null) { - // the variable item is a resource, you could call other operations on this instance as well + Console.WriteLine("Succeeded with null as result"); + } + else + { + // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - FirewallPolicyRuleCollectionGroupData resourceData = item.Data; + FirewallPolicyRuleCollectionGroupData resourceData = result.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } - - Console.WriteLine("Succeeded"); } } } diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyRuleCollectionGroupResource.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyRuleCollectionGroupResource.cs index dbfcdf4365f..4cc7207d212 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyRuleCollectionGroupResource.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_FirewallPolicyRuleCollectionGroupResource.cs @@ -20,10 +20,10 @@ public partial class Sample_FirewallPolicyRuleCollectionGroupResource { [Test] [Ignore("Only validating compilation of examples")] - public async Task Delete_DeleteFirewallPolicyRuleCollectionGroup() + public async Task Get_GetFirewallPolicyNatRuleCollectionGroup() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Delete" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -40,14 +40,18 @@ public async Task Delete_DeleteFirewallPolicyRuleCollectionGroup() FirewallPolicyRuleCollectionGroupResource firewallPolicyRuleCollectionGroup = client.GetFirewallPolicyRuleCollectionGroupResource(firewallPolicyRuleCollectionGroupResourceId); // invoke the operation - await firewallPolicyRuleCollectionGroup.DeleteAsync(WaitUntil.Completed); + FirewallPolicyRuleCollectionGroupResource result = await firewallPolicyRuleCollectionGroup.GetAsync(); - Console.WriteLine("Succeeded"); + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + FirewallPolicyRuleCollectionGroupData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetFirewallPolicyNatRuleCollectionGroup() + public async Task Get_GetFirewallPolicyRuleCollectionGroup() { // Generated from example definition: // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. @@ -78,7 +82,7 @@ public async Task Get_GetFirewallPolicyNatRuleCollectionGroup() [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetFirewallPolicyRuleCollectionGroup() + public async Task Get_GetFirewallPolicyRuleCollectionGroupWithIpGroups() { // Generated from example definition: // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. @@ -93,7 +97,7 @@ public async Task Get_GetFirewallPolicyRuleCollectionGroup() string subscriptionId = "subid"; string resourceGroupName = "rg1"; string firewallPolicyName = "firewallPolicy"; - string ruleCollectionGroupName = "ruleCollectionGroup1"; + string ruleCollectionGroupName = "ruleGroup1"; ResourceIdentifier firewallPolicyRuleCollectionGroupResourceId = FirewallPolicyRuleCollectionGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, firewallPolicyName, ruleCollectionGroupName); FirewallPolicyRuleCollectionGroupResource firewallPolicyRuleCollectionGroup = client.GetFirewallPolicyRuleCollectionGroupResource(firewallPolicyRuleCollectionGroupResourceId); @@ -109,7 +113,7 @@ public async Task Get_GetFirewallPolicyRuleCollectionGroup() [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetFirewallPolicyRuleCollectionGroupWithIpGroups() + public async Task Get_GetFirewallPolicyRuleCollectionGroupWithWebCategories() { // Generated from example definition: // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. @@ -121,10 +125,10 @@ public async Task Get_GetFirewallPolicyRuleCollectionGroupWithIpGroups() // this example assumes you already have this FirewallPolicyRuleCollectionGroupResource created on azure // for more information of creating FirewallPolicyRuleCollectionGroupResource, please refer to the document of FirewallPolicyRuleCollectionGroupResource - string subscriptionId = "subid"; + string subscriptionId = "e747cc13-97d4-4a79-b463-42d7f4e558f2"; string resourceGroupName = "rg1"; string firewallPolicyName = "firewallPolicy"; - string ruleCollectionGroupName = "ruleGroup1"; + string ruleCollectionGroupName = "ruleCollectionGroup1"; ResourceIdentifier firewallPolicyRuleCollectionGroupResourceId = FirewallPolicyRuleCollectionGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, firewallPolicyName, ruleCollectionGroupName); FirewallPolicyRuleCollectionGroupResource firewallPolicyRuleCollectionGroup = client.GetFirewallPolicyRuleCollectionGroupResource(firewallPolicyRuleCollectionGroupResourceId); @@ -140,10 +144,10 @@ public async Task Get_GetFirewallPolicyRuleCollectionGroupWithIpGroups() [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetFirewallPolicyRuleCollectionGroupWithWebCategories() + public async Task Delete_DeleteFirewallPolicyRuleCollectionGroup() { // Generated from example definition: - // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "FirewallPolicyRuleCollectionGroups_Delete" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -152,7 +156,7 @@ public async Task Get_GetFirewallPolicyRuleCollectionGroupWithWebCategories() // this example assumes you already have this FirewallPolicyRuleCollectionGroupResource created on azure // for more information of creating FirewallPolicyRuleCollectionGroupResource, please refer to the document of FirewallPolicyRuleCollectionGroupResource - string subscriptionId = "e747cc13-97d4-4a79-b463-42d7f4e558f2"; + string subscriptionId = "subid"; string resourceGroupName = "rg1"; string firewallPolicyName = "firewallPolicy"; string ruleCollectionGroupName = "ruleCollectionGroup1"; @@ -160,13 +164,9 @@ public async Task Get_GetFirewallPolicyRuleCollectionGroupWithWebCategories() FirewallPolicyRuleCollectionGroupResource firewallPolicyRuleCollectionGroup = client.GetFirewallPolicyRuleCollectionGroupResource(firewallPolicyRuleCollectionGroupResourceId); // invoke the operation - FirewallPolicyRuleCollectionGroupResource result = await firewallPolicyRuleCollectionGroup.GetAsync(); + await firewallPolicyRuleCollectionGroup.DeleteAsync(WaitUntil.Completed); - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - FirewallPolicyRuleCollectionGroupData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + Console.WriteLine("Succeeded"); } [Test] @@ -191,46 +191,26 @@ public async Task Update_CreateFirewallPolicyNatRuleCollectionGroup() FirewallPolicyRuleCollectionGroupResource firewallPolicyRuleCollectionGroup = client.GetFirewallPolicyRuleCollectionGroupResource(firewallPolicyRuleCollectionGroupResourceId); // invoke the operation - FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData() + FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData { Priority = 100, - RuleCollections = -{ -new FirewallPolicyNatRuleCollection() + RuleCollections = {new FirewallPolicyNatRuleCollection { ActionType = FirewallPolicyNatRuleCollectionActionType.Dnat, -Rules = -{ -new NatRule() -{ -IpProtocols = +Rules = {new NatRule { -FirewallPolicyRuleNetworkProtocol.TCP,FirewallPolicyRuleNetworkProtocol.UDP -}, -SourceAddresses = -{ -"2.2.2.2" -}, -DestinationAddresses = -{ -"152.23.32.23" -}, -DestinationPorts = -{ -"8080" -}, +IpProtocols = {FirewallPolicyRuleNetworkProtocol.TCP, FirewallPolicyRuleNetworkProtocol.UDP}, +SourceAddresses = {"2.2.2.2"}, +DestinationAddresses = {"152.23.32.23"}, +DestinationPorts = {"8080"}, TranslatedPort = "8080", -SourceIpGroups = -{ -}, +SourceIpGroups = {}, TranslatedFqdn = "internalhttp.server.net", Name = "nat-rule1", -} -}, +}}, Name = "Example-Nat-Rule-Collection", Priority = 100, -} -}, +}}, }; ArmOperation lro = await firewallPolicyRuleCollectionGroup.UpdateAsync(WaitUntil.Completed, data); FirewallPolicyRuleCollectionGroupResource result = lro.Value; @@ -264,41 +244,23 @@ public async Task Update_CreateFirewallPolicyRuleCollectionGroup() FirewallPolicyRuleCollectionGroupResource firewallPolicyRuleCollectionGroup = client.GetFirewallPolicyRuleCollectionGroupResource(firewallPolicyRuleCollectionGroupResourceId); // invoke the operation - FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData() + FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData { Priority = 100, - RuleCollections = -{ -new FirewallPolicyFilterRuleCollection() + RuleCollections = {new FirewallPolicyFilterRuleCollection { ActionType = FirewallPolicyFilterRuleCollectionActionType.Deny, -Rules = -{ -new NetworkRule() -{ -IpProtocols = +Rules = {new NetworkRule { -FirewallPolicyRuleNetworkProtocol.TCP -}, -SourceAddresses = -{ -"10.1.25.0/24" -}, -DestinationAddresses = -{ -"*" -}, -DestinationPorts = -{ -"*" -}, +IpProtocols = {FirewallPolicyRuleNetworkProtocol.TCP}, +SourceAddresses = {"10.1.25.0/24"}, +DestinationAddresses = {"*"}, +DestinationPorts = {"*"}, Name = "network-rule1", -} -}, +}}, Name = "Example-Filter-Rule-Collection", Priority = 100, -} -}, +}}, }; ArmOperation lro = await firewallPolicyRuleCollectionGroup.UpdateAsync(WaitUntil.Completed, data); FirewallPolicyRuleCollectionGroupResource result = lro.Value; @@ -365,40 +327,22 @@ public async Task Update_CreateFirewallPolicyRuleCollectionGroupWithIpGroups() FirewallPolicyRuleCollectionGroupResource firewallPolicyRuleCollectionGroup = client.GetFirewallPolicyRuleCollectionGroupResource(firewallPolicyRuleCollectionGroupResourceId); // invoke the operation - FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData() + FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData { Priority = 110, - RuleCollections = -{ -new FirewallPolicyFilterRuleCollection() + RuleCollections = {new FirewallPolicyFilterRuleCollection { ActionType = FirewallPolicyFilterRuleCollectionActionType.Deny, -Rules = -{ -new NetworkRule() -{ -IpProtocols = -{ -FirewallPolicyRuleNetworkProtocol.TCP -}, -DestinationPorts = +Rules = {new NetworkRule { -"*" -}, -SourceIpGroups = -{ -"/subscriptions/subid/providers/Microsoft.Network/resourceGroup/rg1/ipGroups/ipGroups1" -}, -DestinationIpGroups = -{ -"/subscriptions/subid/providers/Microsoft.Network/resourceGroup/rg1/ipGroups/ipGroups2" -}, +IpProtocols = {FirewallPolicyRuleNetworkProtocol.TCP}, +DestinationPorts = {"*"}, +SourceIpGroups = {"/subscriptions/subid/providers/Microsoft.Network/resourceGroup/rg1/ipGroups/ipGroups1"}, +DestinationIpGroups = {"/subscriptions/subid/providers/Microsoft.Network/resourceGroup/rg1/ipGroups/ipGroups2"}, Name = "network-1", -} -}, +}}, Name = "Example-Filter-Rule-Collection", -} -}, +}}, }; ArmOperation lro = await firewallPolicyRuleCollectionGroup.UpdateAsync(WaitUntil.Completed, data); FirewallPolicyRuleCollectionGroupResource result = lro.Value; @@ -432,41 +376,26 @@ public async Task Update_CreateFirewallPolicyRuleCollectionGroupWithWebCategorie FirewallPolicyRuleCollectionGroupResource firewallPolicyRuleCollectionGroup = client.GetFirewallPolicyRuleCollectionGroupResource(firewallPolicyRuleCollectionGroupResourceId); // invoke the operation - FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData() + FirewallPolicyRuleCollectionGroupData data = new FirewallPolicyRuleCollectionGroupData { Priority = 110, - RuleCollections = -{ -new FirewallPolicyFilterRuleCollection() + RuleCollections = {new FirewallPolicyFilterRuleCollection { ActionType = FirewallPolicyFilterRuleCollectionActionType.Deny, -Rules = -{ -new ApplicationRule() -{ -SourceAddresses = -{ -"216.58.216.164","10.0.0.0/24" -}, -Protocols = +Rules = {new ApplicationRule { -new FirewallPolicyRuleApplicationProtocol() +SourceAddresses = {"216.58.216.164", "10.0.0.0/24"}, +Protocols = {new FirewallPolicyRuleApplicationProtocol { ProtocolType = FirewallPolicyRuleApplicationProtocolType.Https, Port = 443, -} -}, -WebCategories = -{ -"Hacking" -}, +}}, +WebCategories = {"Hacking"}, Name = "rule1", Description = "Deny inbound rule", -} -}, +}}, Name = "Example-Filter-Rule-Collection", -} -}, +}}, }; ArmOperation lro = await firewallPolicyRuleCollectionGroup.UpdateAsync(WaitUntil.Completed, data); FirewallPolicyRuleCollectionGroupResource result = lro.Value; diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_GuestConfigurationAssignmentCollection.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_GuestConfigurationAssignmentCollection.cs index 021d4fd4d65..726c64f6414 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_GuestConfigurationAssignmentCollection.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_GuestConfigurationAssignmentCollection.cs @@ -30,21 +30,18 @@ public async Task CreateOrUpdate_CreateOrUpdateGuestConfigurationAssignment() // authenticate your client ArmClient client = new ArmClient(cred); - // this example assumes you already have this ArmResource created on azure - // for more information of creating ArmResource, please refer to the document of ArmResource - // get the collection of this GuestConfigurationAssignmentResource string subscriptionId = "mySubscriptionId"; string resourceGroupName = "myResourceGroupName"; string vmName = "myVMName"; - ResourceIdentifier scopeId = new ResourceIdentifier(string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}", subscriptionId, resourceGroupName, vmName)); - GuestConfigurationAssignmentCollection collection = client.GetGuestConfigurationAssignments(scopeId); + string scope = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}"; + GuestConfigurationAssignmentCollection collection = client.GetGuestConfigurationAssignments(new ResourceIdentifier(scope)); // invoke the operation string guestConfigurationAssignmentName = "NotInstalledApplicationForWindows"; - GuestConfigurationAssignmentData data = new GuestConfigurationAssignmentData() + GuestConfigurationAssignmentData data = new GuestConfigurationAssignmentData { - Properties = new GuestConfigurationAssignmentProperties() + Properties = new GuestConfigurationAssignmentProperties { Context = "Azure policy", }, @@ -73,15 +70,12 @@ public async Task Get_GetAGuestConfigurationAssignment() // authenticate your client ArmClient client = new ArmClient(cred); - // this example assumes you already have this ArmResource created on azure - // for more information of creating ArmResource, please refer to the document of ArmResource - // get the collection of this GuestConfigurationAssignmentResource string subscriptionId = "mySubscriptionId"; string resourceGroupName = "myResourceGroupName"; string vmName = "myVMName"; - ResourceIdentifier scopeId = new ResourceIdentifier(string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}", subscriptionId, resourceGroupName, vmName)); - GuestConfigurationAssignmentCollection collection = client.GetGuestConfigurationAssignments(scopeId); + string scope = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}"; + GuestConfigurationAssignmentCollection collection = client.GetGuestConfigurationAssignments(new ResourceIdentifier(scope)); // invoke the operation string guestConfigurationAssignmentName = "SecureProtocol"; @@ -96,36 +90,39 @@ public async Task Get_GetAGuestConfigurationAssignment() [Test] [Ignore("Only validating compilation of examples")] - public async Task Exists_GetAGuestConfigurationAssignment() + public async Task GetAll_ListAllGuestConfigurationAssignmentsForAVirtualMachine() { // Generated from example definition: - // this example is just showing the usage of "GuestConfigurationAssignments_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "GuestConfigurationAssignments_List" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); // authenticate your client ArmClient client = new ArmClient(cred); - // this example assumes you already have this ArmResource created on azure - // for more information of creating ArmResource, please refer to the document of ArmResource - // get the collection of this GuestConfigurationAssignmentResource string subscriptionId = "mySubscriptionId"; string resourceGroupName = "myResourceGroupName"; string vmName = "myVMName"; - ResourceIdentifier scopeId = new ResourceIdentifier(string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}", subscriptionId, resourceGroupName, vmName)); - GuestConfigurationAssignmentCollection collection = client.GetGuestConfigurationAssignments(scopeId); + string scope = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}"; + GuestConfigurationAssignmentCollection collection = client.GetGuestConfigurationAssignments(new ResourceIdentifier(scope)); - // invoke the operation - string guestConfigurationAssignmentName = "SecureProtocol"; - bool result = await collection.ExistsAsync(guestConfigurationAssignmentName); + // invoke the operation and iterate over the result + await foreach (GuestConfigurationAssignmentResource item in collection.GetAllAsync()) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + GuestConfigurationAssignmentData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } - Console.WriteLine($"Succeeded: {result}"); + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetIfExists_GetAGuestConfigurationAssignment() + public async Task Exists_GetAGuestConfigurationAssignment() { // Generated from example definition: // this example is just showing the usage of "GuestConfigurationAssignments_Get" operation, for the dependent resources, they will have to be created separately. @@ -135,68 +132,56 @@ public async Task GetIfExists_GetAGuestConfigurationAssignment() // authenticate your client ArmClient client = new ArmClient(cred); - // this example assumes you already have this ArmResource created on azure - // for more information of creating ArmResource, please refer to the document of ArmResource - // get the collection of this GuestConfigurationAssignmentResource string subscriptionId = "mySubscriptionId"; string resourceGroupName = "myResourceGroupName"; string vmName = "myVMName"; - ResourceIdentifier scopeId = new ResourceIdentifier(string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}", subscriptionId, resourceGroupName, vmName)); - GuestConfigurationAssignmentCollection collection = client.GetGuestConfigurationAssignments(scopeId); + string scope = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}"; + GuestConfigurationAssignmentCollection collection = client.GetGuestConfigurationAssignments(new ResourceIdentifier(scope)); // invoke the operation string guestConfigurationAssignmentName = "SecureProtocol"; - NullableResponse response = await collection.GetIfExistsAsync(guestConfigurationAssignmentName); - GuestConfigurationAssignmentResource result = response.HasValue ? response.Value : null; + bool result = await collection.ExistsAsync(guestConfigurationAssignmentName); - if (result == null) - { - Console.WriteLine("Succeeded with null as result"); - } - else - { - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - GuestConfigurationAssignmentData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } + Console.WriteLine($"Succeeded: {result}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetAll_ListAllGuestConfigurationAssignmentsForAVirtualMachine() + public async Task GetIfExists_GetAGuestConfigurationAssignment() { // Generated from example definition: - // this example is just showing the usage of "GuestConfigurationAssignments_List" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "GuestConfigurationAssignments_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); // authenticate your client ArmClient client = new ArmClient(cred); - // this example assumes you already have this ArmResource created on azure - // for more information of creating ArmResource, please refer to the document of ArmResource - // get the collection of this GuestConfigurationAssignmentResource string subscriptionId = "mySubscriptionId"; string resourceGroupName = "myResourceGroupName"; string vmName = "myVMName"; - ResourceIdentifier scopeId = new ResourceIdentifier(string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}", subscriptionId, resourceGroupName, vmName)); - GuestConfigurationAssignmentCollection collection = client.GetGuestConfigurationAssignments(scopeId); + string scope = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}"; + GuestConfigurationAssignmentCollection collection = client.GetGuestConfigurationAssignments(new ResourceIdentifier(scope)); - // invoke the operation and iterate over the result - await foreach (GuestConfigurationAssignmentResource item in collection.GetAllAsync()) + // invoke the operation + string guestConfigurationAssignmentName = "SecureProtocol"; + NullableResponse response = await collection.GetIfExistsAsync(guestConfigurationAssignmentName); + GuestConfigurationAssignmentResource result = response.HasValue ? response.Value : null; + + if (result == null) { - // the variable item is a resource, you could call other operations on this instance as well + Console.WriteLine("Succeeded with null as result"); + } + else + { + // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - GuestConfigurationAssignmentData resourceData = item.Data; + GuestConfigurationAssignmentData resourceData = result.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } - - Console.WriteLine("Succeeded"); } } } diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_GuestConfigurationAssignmentResource.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_GuestConfigurationAssignmentResource.cs index 10a278fd223..3b3aa9118a1 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_GuestConfigurationAssignmentResource.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_GuestConfigurationAssignmentResource.cs @@ -20,10 +20,10 @@ public partial class Sample_GuestConfigurationAssignmentResource { [Test] [Ignore("Only validating compilation of examples")] - public async Task Update_CreateOrUpdateGuestConfigurationAssignment() + public async Task Get_GetAGuestConfigurationAssignment() { // Generated from example definition: - // this example is just showing the usage of "GuestConfigurationAssignments_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "GuestConfigurationAssignments_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -35,22 +35,12 @@ public async Task Update_CreateOrUpdateGuestConfigurationAssignment() string subscriptionId = "mySubscriptionId"; string resourceGroupName = "myResourceGroupName"; string vmName = "myVMName"; - string guestConfigurationAssignmentName = "NotInstalledApplicationForWindows"; + string guestConfigurationAssignmentName = "SecureProtocol"; ResourceIdentifier guestConfigurationAssignmentResourceId = GuestConfigurationAssignmentResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, vmName, guestConfigurationAssignmentName); GuestConfigurationAssignmentResource guestConfigurationAssignment = client.GetGuestConfigurationAssignmentResource(guestConfigurationAssignmentResourceId); // invoke the operation - GuestConfigurationAssignmentData data = new GuestConfigurationAssignmentData() - { - Properties = new GuestConfigurationAssignmentProperties() - { - Context = "Azure policy", - }, - Name = "NotInstalledApplicationForWindows", - Location = new AzureLocation("westcentralus"), - }; - ArmOperation lro = await guestConfigurationAssignment.UpdateAsync(WaitUntil.Completed, data); - GuestConfigurationAssignmentResource result = lro.Value; + GuestConfigurationAssignmentResource result = await guestConfigurationAssignment.GetAsync(); // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance @@ -61,10 +51,10 @@ public async Task Update_CreateOrUpdateGuestConfigurationAssignment() [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetAGuestConfigurationAssignment() + public async Task Delete_DeleteAnGuestConfigurationAssignment() { // Generated from example definition: - // this example is just showing the usage of "GuestConfigurationAssignments_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "GuestConfigurationAssignments_Delete" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -81,21 +71,17 @@ public async Task Get_GetAGuestConfigurationAssignment() GuestConfigurationAssignmentResource guestConfigurationAssignment = client.GetGuestConfigurationAssignmentResource(guestConfigurationAssignmentResourceId); // invoke the operation - GuestConfigurationAssignmentResource result = await guestConfigurationAssignment.GetAsync(); + await guestConfigurationAssignment.DeleteAsync(WaitUntil.Completed); - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - GuestConfigurationAssignmentData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Delete_DeleteAnGuestConfigurationAssignment() + public async Task Update_CreateOrUpdateGuestConfigurationAssignment() { // Generated from example definition: - // this example is just showing the usage of "GuestConfigurationAssignments_Delete" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "GuestConfigurationAssignments_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -107,14 +93,28 @@ public async Task Delete_DeleteAnGuestConfigurationAssignment() string subscriptionId = "mySubscriptionId"; string resourceGroupName = "myResourceGroupName"; string vmName = "myVMName"; - string guestConfigurationAssignmentName = "SecureProtocol"; + string guestConfigurationAssignmentName = "NotInstalledApplicationForWindows"; ResourceIdentifier guestConfigurationAssignmentResourceId = GuestConfigurationAssignmentResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, vmName, guestConfigurationAssignmentName); GuestConfigurationAssignmentResource guestConfigurationAssignment = client.GetGuestConfigurationAssignmentResource(guestConfigurationAssignmentResourceId); // invoke the operation - await guestConfigurationAssignment.DeleteAsync(WaitUntil.Completed); + GuestConfigurationAssignmentData data = new GuestConfigurationAssignmentData + { + Properties = new GuestConfigurationAssignmentProperties + { + Context = "Azure policy", + }, + Name = "NotInstalledApplicationForWindows", + Location = new AzureLocation("westcentralus"), + }; + ArmOperation lro = await guestConfigurationAssignment.UpdateAsync(WaitUntil.Completed, data); + GuestConfigurationAssignmentResource result = lro.Value; - Console.WriteLine("Succeeded"); + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + GuestConfigurationAssignmentData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } } } diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_ManagedHsmCollection.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_ManagedHsmCollection.cs index 6c590915c62..eaab3911e1d 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_ManagedHsmCollection.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_ManagedHsmCollection.cs @@ -6,7 +6,7 @@ #nullable disable using System; -using System.Collections.Generic; +using System.Text; using System.Threading.Tasks; using Azure; using Azure.Core; @@ -47,45 +47,44 @@ public async Task CreateOrUpdate_CreateANewManagedHSMPoolOrUpdateAnExistingManag string name = "hsm1"; ManagedHsmData data = new ManagedHsmData(new AzureLocation("westus")) { - Properties = new ManagedHsmProperties() + Properties = new ManagedHsmProperties { - Settings = BinaryData.FromString("\"{\"config1\":\"value1\",\"config2\":8427,\"config3\":false,\"config4\":[\"1\",\"2\"],\"config5\":{\"inner\":\"something\"}}\""), - ProtectedSettings = BinaryData.FromObjectAsJson(new Dictionary() + Settings = BinaryData.FromObjectAsJson("{\"config1\":\"value1\",\"config2\":8427,\"config3\":false,\"config4\":[\"1\",\"2\"],\"config5\":{\"inner\":\"something\"}}"), + ProtectedSettings = BinaryData.FromObjectAsJson(new { - ["protected1"] = "value2", - ["protected2"] = "10", - ["protected3"] = "false", - ["protected4"] = new object[] { "1", "2", "3" }, - ["protected5"] = new Dictionary() + protected1 = "value2", + protected2 = "10", + protected3 = "false", + protected4 = new object[] + { +"1", +"2", +"3" + }, + protected5 = new { - ["protectedInner"] = "something else" - } + protectedInner = "something else", + }, }), - RawMessage = Convert.FromBase64String("PFX-or-PEM-blob"), + RawMessage = Encoding.UTF8.GetBytes("PFX-or-PEM-blob"), TenantId = Guid.Parse("00000000-0000-0000-0000-000000000000"), - InitialAdminObjectIds = -{ -"00000000-0000-0000-0000-000000000000" -}, + InitialAdminObjectIds = { "00000000-0000-0000-0000-000000000000" }, EnableSoftDelete = true, SoftDeleteRetentionInDays = 90, EnablePurgeProtection = true, - NetworkAcls = new MhsmNetworkRuleSet() + NetworkAcls = new MhsmNetworkRuleSet { - VirtualNetworkRules = -{ -new WritableSubResource() + VirtualNetworkRules = {new WritableSubResource { Id = new ResourceIdentifier("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/hsm-group/providers/Microsoft.Network/virtualNetworks/vnet1/subnets/default"), -} -}, +}}, }, }, Sku = new ManagedHsmSku(ManagedHsmSkuFamily.B, ManagedHsmSkuName.StandardB1), Tags = { ["Dept"] = "hsm", -["Environment"] = "dogfood", +["Environment"] = "dogfood" }, }; ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, name, data); @@ -133,10 +132,10 @@ public async Task Get_RetrieveAManagedHSMPool() [Test] [Ignore("Only validating compilation of examples")] - public async Task Exists_RetrieveAManagedHSMPool() + public async Task GetAll_ListManagedHSMPoolsInAResourceGroup() { // Generated from example definition: - // this example is just showing the usage of "ManagedHsms_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "ManagedHsms_ListByResourceGroup" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -153,16 +152,22 @@ public async Task Exists_RetrieveAManagedHSMPool() // get the collection of this ManagedHsmResource ManagedHsmCollection collection = resourceGroupResource.GetManagedHsms(); - // invoke the operation - string name = "hsm1"; - bool result = await collection.ExistsAsync(name); + // invoke the operation and iterate over the result + await foreach (ManagedHsmResource item in collection.GetAllAsync()) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + ManagedHsmData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } - Console.WriteLine($"Succeeded: {result}"); + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetIfExists_RetrieveAManagedHSMPool() + public async Task Exists_RetrieveAManagedHSMPool() { // Generated from example definition: // this example is just showing the usage of "ManagedHsms_Get" operation, for the dependent resources, they will have to be created separately. @@ -184,29 +189,17 @@ public async Task GetIfExists_RetrieveAManagedHSMPool() // invoke the operation string name = "hsm1"; - NullableResponse response = await collection.GetIfExistsAsync(name); - ManagedHsmResource result = response.HasValue ? response.Value : null; + bool result = await collection.ExistsAsync(name); - if (result == null) - { - Console.WriteLine("Succeeded with null as result"); - } - else - { - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - ManagedHsmData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } + Console.WriteLine($"Succeeded: {result}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetAll_ListManagedHSMPoolsInAResourceGroup() + public async Task GetIfExists_RetrieveAManagedHSMPool() { // Generated from example definition: - // this example is just showing the usage of "ManagedHsms_ListByResourceGroup" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "ManagedHsms_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -223,17 +216,23 @@ public async Task GetAll_ListManagedHSMPoolsInAResourceGroup() // get the collection of this ManagedHsmResource ManagedHsmCollection collection = resourceGroupResource.GetManagedHsms(); - // invoke the operation and iterate over the result - await foreach (ManagedHsmResource item in collection.GetAllAsync()) + // invoke the operation + string name = "hsm1"; + NullableResponse response = await collection.GetIfExistsAsync(name); + ManagedHsmResource result = response.HasValue ? response.Value : null; + + if (result == null) { - // the variable item is a resource, you could call other operations on this instance as well + Console.WriteLine("Succeeded with null as result"); + } + else + { + // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - ManagedHsmData resourceData = item.Data; + ManagedHsmData resourceData = result.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } - - Console.WriteLine("Succeeded"); } } } diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_ManagedHsmResource.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_ManagedHsmResource.cs index 6ce9ae085f6..134ae67d11b 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_ManagedHsmResource.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_ManagedHsmResource.cs @@ -11,7 +11,6 @@ using Azure.Core; using Azure.Identity; using Azure.ResourceManager; -using Azure.ResourceManager.Resources; using MgmtMockAndSample.Models; using NUnit.Framework; @@ -21,10 +20,10 @@ public partial class Sample_ManagedHsmResource { [Test] [Ignore("Only validating compilation of examples")] - public async Task Update_UpdateAnExistingManagedHSMPool() + public async Task Get_RetrieveAManagedHSMPool() { // Generated from example definition: - // this example is just showing the usage of "ManagedHsms_Update" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "ManagedHsms_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -40,17 +39,7 @@ public async Task Update_UpdateAnExistingManagedHSMPool() ManagedHsmResource managedHsm = client.GetManagedHsmResource(managedHsmResourceId); // invoke the operation - ManagedHsmData data = new ManagedHsmData(new AzureLocation("placeholder")) - { - Tags = -{ -["Dept"] = "hsm", -["Environment"] = "dogfood", -["Slice"] = "A", -}, - }; - ArmOperation lro = await managedHsm.UpdateAsync(WaitUntil.Completed, data); - ManagedHsmResource result = lro.Value; + ManagedHsmResource result = await managedHsm.GetAsync(); // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance @@ -87,10 +76,10 @@ public async Task Delete_DeleteAManagedHSMPool() [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_RetrieveAManagedHSMPool() + public async Task Update_UpdateAnExistingManagedHSMPool() { // Generated from example definition: - // this example is just showing the usage of "ManagedHsms_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "ManagedHsms_Update" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -106,7 +95,17 @@ public async Task Get_RetrieveAManagedHSMPool() ManagedHsmResource managedHsm = client.GetManagedHsmResource(managedHsmResourceId); // invoke the operation - ManagedHsmResource result = await managedHsm.GetAsync(); + ManagedHsmData data = new ManagedHsmData(default) + { + Tags = +{ +["Dept"] = "hsm", +["Environment"] = "dogfood", +["Slice"] = "A" +}, + }; + ArmOperation lro = await managedHsm.UpdateAsync(WaitUntil.Completed, data); + ManagedHsmResource result = lro.Value; // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance @@ -115,37 +114,6 @@ public async Task Get_RetrieveAManagedHSMPool() Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } - [Test] - [Ignore("Only validating compilation of examples")] - public async Task GetManagedHsms_ListManagedHSMPoolsInASubscription() - { - // Generated from example definition: - // this example is just showing the usage of "ManagedHsms_ListBySubscription" operation, for the dependent resources, they will have to be created separately. - - // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line - TokenCredential cred = new DefaultAzureCredential(); - // authenticate your client - ArmClient client = new ArmClient(cred); - - // this example assumes you already have this SubscriptionResource created on azure - // for more information of creating SubscriptionResource, please refer to the document of SubscriptionResource - string subscriptionId = "00000000-0000-0000-0000-000000000000"; - ResourceIdentifier subscriptionResourceId = SubscriptionResource.CreateResourceIdentifier(subscriptionId); - SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); - - // invoke the operation and iterate over the result - await foreach (ManagedHsmResource item in subscriptionResource.GetManagedHsmsAsync()) - { - // the variable item is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - ManagedHsmData resourceData = item.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } - - Console.WriteLine("Succeeded"); - } - [Test] [Ignore("Only validating compilation of examples")] public async Task GetMHSMPrivateLinkResourcesByMhsmResource_KeyVaultListPrivateLinkResources() diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MgmtMockAndSamplePrivateEndpointConnectionCollection.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MgmtMockAndSamplePrivateEndpointConnectionCollection.cs index 7a4223615e4..f50203fa459 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MgmtMockAndSamplePrivateEndpointConnectionCollection.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MgmtMockAndSamplePrivateEndpointConnectionCollection.cs @@ -20,10 +20,10 @@ public partial class Sample_MgmtMockAndSamplePrivateEndpointConnectionCollection { [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_KeyVaultGetPrivateEndpointConnection() + public async Task CreateOrUpdate_KeyVaultPutPrivateEndpointConnection() { // Generated from example definition: - // this example is just showing the usage of "PrivateEndpointConnections_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "PrivateEndpointConnections_Put" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -43,7 +43,17 @@ public async Task Get_KeyVaultGetPrivateEndpointConnection() // invoke the operation string privateEndpointConnectionName = "sample-pec"; - MgmtMockAndSamplePrivateEndpointConnectionResource result = await collection.GetAsync(privateEndpointConnectionName); + MgmtMockAndSamplePrivateEndpointConnectionData data = new MgmtMockAndSamplePrivateEndpointConnectionData + { + Etag = "", + ConnectionState = new MgmtMockAndSamplePrivateLinkServiceConnectionState + { + Status = MgmtMockAndSamplePrivateEndpointServiceConnectionStatus.Approved, + Description = "My name is Joe and I'm approving this.", + }, + }; + ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, privateEndpointConnectionName, data); + MgmtMockAndSamplePrivateEndpointConnectionResource result = lro.Value; // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance @@ -54,7 +64,7 @@ public async Task Get_KeyVaultGetPrivateEndpointConnection() [Test] [Ignore("Only validating compilation of examples")] - public async Task Exists_KeyVaultGetPrivateEndpointConnection() + public async Task Get_KeyVaultGetPrivateEndpointConnection() { // Generated from example definition: // this example is just showing the usage of "PrivateEndpointConnections_Get" operation, for the dependent resources, they will have to be created separately. @@ -77,17 +87,21 @@ public async Task Exists_KeyVaultGetPrivateEndpointConnection() // invoke the operation string privateEndpointConnectionName = "sample-pec"; - bool result = await collection.ExistsAsync(privateEndpointConnectionName); + MgmtMockAndSamplePrivateEndpointConnectionResource result = await collection.GetAsync(privateEndpointConnectionName); - Console.WriteLine($"Succeeded: {result}"); + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + MgmtMockAndSamplePrivateEndpointConnectionData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetIfExists_KeyVaultGetPrivateEndpointConnection() + public async Task GetAll_KeyVaultListPrivateEndpointConnection() { // Generated from example definition: - // this example is just showing the usage of "PrivateEndpointConnections_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "PrivateEndpointConnections_ListByResource" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -105,31 +119,25 @@ public async Task GetIfExists_KeyVaultGetPrivateEndpointConnection() // get the collection of this MgmtMockAndSamplePrivateEndpointConnectionResource MgmtMockAndSamplePrivateEndpointConnectionCollection collection = vault.GetMgmtMockAndSamplePrivateEndpointConnections(); - // invoke the operation - string privateEndpointConnectionName = "sample-pec"; - NullableResponse response = await collection.GetIfExistsAsync(privateEndpointConnectionName); - MgmtMockAndSamplePrivateEndpointConnectionResource result = response.HasValue ? response.Value : null; - - if (result == null) - { - Console.WriteLine("Succeeded with null as result"); - } - else + // invoke the operation and iterate over the result + await foreach (MgmtMockAndSamplePrivateEndpointConnectionResource item in collection.GetAllAsync()) { - // the variable result is a resource, you could call other operations on this instance as well + // the variable item is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - MgmtMockAndSamplePrivateEndpointConnectionData resourceData = result.Data; + MgmtMockAndSamplePrivateEndpointConnectionData resourceData = item.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } + + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task CreateOrUpdate_KeyVaultPutPrivateEndpointConnection() + public async Task Exists_KeyVaultGetPrivateEndpointConnection() { // Generated from example definition: - // this example is just showing the usage of "PrivateEndpointConnections_Put" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "PrivateEndpointConnections_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -149,31 +157,17 @@ public async Task CreateOrUpdate_KeyVaultPutPrivateEndpointConnection() // invoke the operation string privateEndpointConnectionName = "sample-pec"; - MgmtMockAndSamplePrivateEndpointConnectionData data = new MgmtMockAndSamplePrivateEndpointConnectionData() - { - Etag = "", - ConnectionState = new MgmtMockAndSamplePrivateLinkServiceConnectionState() - { - Status = MgmtMockAndSamplePrivateEndpointServiceConnectionStatus.Approved, - Description = "My name is Joe and I'm approving this.", - }, - }; - ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, privateEndpointConnectionName, data); - MgmtMockAndSamplePrivateEndpointConnectionResource result = lro.Value; + bool result = await collection.ExistsAsync(privateEndpointConnectionName); - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - MgmtMockAndSamplePrivateEndpointConnectionData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + Console.WriteLine($"Succeeded: {result}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetAll_KeyVaultListPrivateEndpointConnection() + public async Task GetIfExists_KeyVaultGetPrivateEndpointConnection() { // Generated from example definition: - // this example is just showing the usage of "PrivateEndpointConnections_ListByResource" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "PrivateEndpointConnections_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -191,17 +185,23 @@ public async Task GetAll_KeyVaultListPrivateEndpointConnection() // get the collection of this MgmtMockAndSamplePrivateEndpointConnectionResource MgmtMockAndSamplePrivateEndpointConnectionCollection collection = vault.GetMgmtMockAndSamplePrivateEndpointConnections(); - // invoke the operation and iterate over the result - await foreach (MgmtMockAndSamplePrivateEndpointConnectionResource item in collection.GetAllAsync()) + // invoke the operation + string privateEndpointConnectionName = "sample-pec"; + NullableResponse response = await collection.GetIfExistsAsync(privateEndpointConnectionName); + MgmtMockAndSamplePrivateEndpointConnectionResource result = response.HasValue ? response.Value : null; + + if (result == null) { - // the variable item is a resource, you could call other operations on this instance as well + Console.WriteLine("Succeeded with null as result"); + } + else + { + // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - MgmtMockAndSamplePrivateEndpointConnectionData resourceData = item.Data; + MgmtMockAndSamplePrivateEndpointConnectionData resourceData = result.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } - - Console.WriteLine("Succeeded"); } } } diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MgmtMockAndSamplePrivateEndpointConnectionResource.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MgmtMockAndSamplePrivateEndpointConnectionResource.cs index 65dab862232..b6adfc4f7c5 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MgmtMockAndSamplePrivateEndpointConnectionResource.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MgmtMockAndSamplePrivateEndpointConnectionResource.cs @@ -51,10 +51,10 @@ public async Task Get_KeyVaultGetPrivateEndpointConnection() [Test] [Ignore("Only validating compilation of examples")] - public async Task Update_KeyVaultPutPrivateEndpointConnection() + public async Task Delete_KeyVaultDeletePrivateEndpointConnection() { // Generated from example definition: - // this example is just showing the usage of "PrivateEndpointConnections_Put" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "PrivateEndpointConnections_Delete" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -71,16 +71,7 @@ public async Task Update_KeyVaultPutPrivateEndpointConnection() MgmtMockAndSamplePrivateEndpointConnectionResource mgmtMockAndSamplePrivateEndpointConnection = client.GetMgmtMockAndSamplePrivateEndpointConnectionResource(mgmtMockAndSamplePrivateEndpointConnectionResourceId); // invoke the operation - MgmtMockAndSamplePrivateEndpointConnectionData data = new MgmtMockAndSamplePrivateEndpointConnectionData() - { - Etag = "", - ConnectionState = new MgmtMockAndSamplePrivateLinkServiceConnectionState() - { - Status = MgmtMockAndSamplePrivateEndpointServiceConnectionStatus.Approved, - Description = "My name is Joe and I'm approving this.", - }, - }; - ArmOperation lro = await mgmtMockAndSamplePrivateEndpointConnection.UpdateAsync(WaitUntil.Completed, data); + ArmOperation lro = await mgmtMockAndSamplePrivateEndpointConnection.DeleteAsync(WaitUntil.Completed); MgmtMockAndSamplePrivateEndpointConnectionResource result = lro.Value; // the variable result is a resource, you could call other operations on this instance as well @@ -92,10 +83,10 @@ public async Task Update_KeyVaultPutPrivateEndpointConnection() [Test] [Ignore("Only validating compilation of examples")] - public async Task Delete_KeyVaultDeletePrivateEndpointConnection() + public async Task Update_KeyVaultPutPrivateEndpointConnection() { // Generated from example definition: - // this example is just showing the usage of "PrivateEndpointConnections_Delete" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "PrivateEndpointConnections_Put" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -112,7 +103,16 @@ public async Task Delete_KeyVaultDeletePrivateEndpointConnection() MgmtMockAndSamplePrivateEndpointConnectionResource mgmtMockAndSamplePrivateEndpointConnection = client.GetMgmtMockAndSamplePrivateEndpointConnectionResource(mgmtMockAndSamplePrivateEndpointConnectionResourceId); // invoke the operation - ArmOperation lro = await mgmtMockAndSamplePrivateEndpointConnection.DeleteAsync(WaitUntil.Completed); + MgmtMockAndSamplePrivateEndpointConnectionData data = new MgmtMockAndSamplePrivateEndpointConnectionData + { + Etag = "", + ConnectionState = new MgmtMockAndSamplePrivateLinkServiceConnectionState + { + Status = MgmtMockAndSamplePrivateEndpointServiceConnectionStatus.Approved, + Description = "My name is Joe and I'm approving this.", + }, + }; + ArmOperation lro = await mgmtMockAndSamplePrivateEndpointConnection.UpdateAsync(WaitUntil.Completed, data); MgmtMockAndSamplePrivateEndpointConnectionResource result = lro.Value; // the variable result is a resource, you could call other operations on this instance as well diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MhsmPrivateEndpointConnectionCollection.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MhsmPrivateEndpointConnectionCollection.cs index 1e49579f747..bed5f03b190 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MhsmPrivateEndpointConnectionCollection.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MhsmPrivateEndpointConnectionCollection.cs @@ -20,10 +20,10 @@ public partial class Sample_MhsmPrivateEndpointConnectionCollection { [Test] [Ignore("Only validating compilation of examples")] - public async Task GetAll_ListManagedHSMPoolsInASubscription() + public async Task CreateOrUpdate_ManagedHsmPutPrivateEndpointConnection() { // Generated from example definition: - // this example is just showing the usage of "MHSMPrivateEndpointConnections_ListByResource" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "MHSMPrivateEndpointConnections_Put" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -41,17 +41,24 @@ public async Task GetAll_ListManagedHSMPoolsInASubscription() // get the collection of this MhsmPrivateEndpointConnectionResource MhsmPrivateEndpointConnectionCollection collection = managedHsm.GetMhsmPrivateEndpointConnections(); - // invoke the operation and iterate over the result - await foreach (MhsmPrivateEndpointConnectionResource item in collection.GetAllAsync()) + // invoke the operation + string privateEndpointConnectionName = "sample-pec"; + MhsmPrivateEndpointConnectionData data = new MhsmPrivateEndpointConnectionData(default) { - // the variable item is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - MhsmPrivateEndpointConnectionData resourceData = item.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } + PrivateLinkServiceConnectionState = new MhsmPrivateLinkServiceConnectionState + { + Status = MgmtMockAndSamplePrivateEndpointServiceConnectionStatus.Approved, + Description = "My name is Joe and I'm approving this.", + }, + }; + ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, privateEndpointConnectionName, data); + MhsmPrivateEndpointConnectionResource result = lro.Value; - Console.WriteLine("Succeeded"); + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + MhsmPrivateEndpointConnectionData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } [Test] @@ -90,10 +97,10 @@ public async Task Get_ManagedHsmGetPrivateEndpointConnection() [Test] [Ignore("Only validating compilation of examples")] - public async Task Exists_ManagedHsmGetPrivateEndpointConnection() + public async Task GetAll_ListManagedHSMPoolsInASubscription() { // Generated from example definition: - // this example is just showing the usage of "MHSMPrivateEndpointConnections_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "MHSMPrivateEndpointConnections_ListByResource" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -111,16 +118,22 @@ public async Task Exists_ManagedHsmGetPrivateEndpointConnection() // get the collection of this MhsmPrivateEndpointConnectionResource MhsmPrivateEndpointConnectionCollection collection = managedHsm.GetMhsmPrivateEndpointConnections(); - // invoke the operation - string privateEndpointConnectionName = "sample-pec"; - bool result = await collection.ExistsAsync(privateEndpointConnectionName); + // invoke the operation and iterate over the result + await foreach (MhsmPrivateEndpointConnectionResource item in collection.GetAllAsync()) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + MhsmPrivateEndpointConnectionData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } - Console.WriteLine($"Succeeded: {result}"); + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetIfExists_ManagedHsmGetPrivateEndpointConnection() + public async Task Exists_ManagedHsmGetPrivateEndpointConnection() { // Generated from example definition: // this example is just showing the usage of "MHSMPrivateEndpointConnections_Get" operation, for the dependent resources, they will have to be created separately. @@ -143,29 +156,17 @@ public async Task GetIfExists_ManagedHsmGetPrivateEndpointConnection() // invoke the operation string privateEndpointConnectionName = "sample-pec"; - NullableResponse response = await collection.GetIfExistsAsync(privateEndpointConnectionName); - MhsmPrivateEndpointConnectionResource result = response.HasValue ? response.Value : null; + bool result = await collection.ExistsAsync(privateEndpointConnectionName); - if (result == null) - { - Console.WriteLine("Succeeded with null as result"); - } - else - { - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - MhsmPrivateEndpointConnectionData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } + Console.WriteLine($"Succeeded: {result}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task CreateOrUpdate_ManagedHsmPutPrivateEndpointConnection() + public async Task GetIfExists_ManagedHsmGetPrivateEndpointConnection() { // Generated from example definition: - // this example is just showing the usage of "MHSMPrivateEndpointConnections_Put" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "MHSMPrivateEndpointConnections_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -185,22 +186,21 @@ public async Task CreateOrUpdate_ManagedHsmPutPrivateEndpointConnection() // invoke the operation string privateEndpointConnectionName = "sample-pec"; - MhsmPrivateEndpointConnectionData data = new MhsmPrivateEndpointConnectionData(new AzureLocation("placeholder")) - { - PrivateLinkServiceConnectionState = new MhsmPrivateLinkServiceConnectionState() - { - Status = MgmtMockAndSamplePrivateEndpointServiceConnectionStatus.Approved, - Description = "My name is Joe and I'm approving this.", - }, - }; - ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, privateEndpointConnectionName, data); - MhsmPrivateEndpointConnectionResource result = lro.Value; + NullableResponse response = await collection.GetIfExistsAsync(privateEndpointConnectionName); + MhsmPrivateEndpointConnectionResource result = response.HasValue ? response.Value : null; - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - MhsmPrivateEndpointConnectionData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + if (result == null) + { + Console.WriteLine("Succeeded with null as result"); + } + else + { + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + MhsmPrivateEndpointConnectionData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } } } } diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MhsmPrivateEndpointConnectionResource.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MhsmPrivateEndpointConnectionResource.cs index 698a7744403..ef4487a0be7 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MhsmPrivateEndpointConnectionResource.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_MhsmPrivateEndpointConnectionResource.cs @@ -51,10 +51,10 @@ public async Task Get_ManagedHsmGetPrivateEndpointConnection() [Test] [Ignore("Only validating compilation of examples")] - public async Task Update_ManagedHsmPutPrivateEndpointConnection() + public async Task Delete_ManagedHsmDeletePrivateEndpointConnection() { // Generated from example definition: - // this example is just showing the usage of "MHSMPrivateEndpointConnections_Put" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "MHSMPrivateEndpointConnections_Delete" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -71,15 +71,7 @@ public async Task Update_ManagedHsmPutPrivateEndpointConnection() MhsmPrivateEndpointConnectionResource mhsmPrivateEndpointConnection = client.GetMhsmPrivateEndpointConnectionResource(mhsmPrivateEndpointConnectionResourceId); // invoke the operation - MhsmPrivateEndpointConnectionData data = new MhsmPrivateEndpointConnectionData(new AzureLocation("placeholder")) - { - PrivateLinkServiceConnectionState = new MhsmPrivateLinkServiceConnectionState() - { - Status = MgmtMockAndSamplePrivateEndpointServiceConnectionStatus.Approved, - Description = "My name is Joe and I'm approving this.", - }, - }; - ArmOperation lro = await mhsmPrivateEndpointConnection.UpdateAsync(WaitUntil.Completed, data); + ArmOperation lro = await mhsmPrivateEndpointConnection.DeleteAsync(WaitUntil.Completed); MhsmPrivateEndpointConnectionResource result = lro.Value; // the variable result is a resource, you could call other operations on this instance as well @@ -91,10 +83,10 @@ public async Task Update_ManagedHsmPutPrivateEndpointConnection() [Test] [Ignore("Only validating compilation of examples")] - public async Task Delete_ManagedHsmDeletePrivateEndpointConnection() + public async Task Update_ManagedHsmPutPrivateEndpointConnection() { // Generated from example definition: - // this example is just showing the usage of "MHSMPrivateEndpointConnections_Delete" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "MHSMPrivateEndpointConnections_Put" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -111,7 +103,15 @@ public async Task Delete_ManagedHsmDeletePrivateEndpointConnection() MhsmPrivateEndpointConnectionResource mhsmPrivateEndpointConnection = client.GetMhsmPrivateEndpointConnectionResource(mhsmPrivateEndpointConnectionResourceId); // invoke the operation - ArmOperation lro = await mhsmPrivateEndpointConnection.DeleteAsync(WaitUntil.Completed); + MhsmPrivateEndpointConnectionData data = new MhsmPrivateEndpointConnectionData(default) + { + PrivateLinkServiceConnectionState = new MhsmPrivateLinkServiceConnectionState + { + Status = MgmtMockAndSamplePrivateEndpointServiceConnectionStatus.Approved, + Description = "My name is Joe and I'm approving this.", + }, + }; + ArmOperation lro = await mhsmPrivateEndpointConnection.UpdateAsync(WaitUntil.Completed, data); MhsmPrivateEndpointConnectionResource result = lro.Value; // the variable result is a resource, you could call other operations on this instance as well diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_RoleAssignmentCollection.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_RoleAssignmentCollection.cs index 460aa5645ca..f82c8200a21 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_RoleAssignmentCollection.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_RoleAssignmentCollection.cs @@ -30,17 +30,13 @@ public async Task CreateOrUpdate_CreateRoleAssignment() // authenticate your client ArmClient client = new ArmClient(cred); - // this example assumes you already have this ArmResource created on azure - // for more information of creating ArmResource, please refer to the document of ArmResource - // get the collection of this RoleAssignmentResource string scope = "scope"; - ResourceIdentifier scopeId = new ResourceIdentifier(string.Format("/{0}", scope)); - RoleAssignmentCollection collection = client.GetRoleAssignments(scopeId); + RoleAssignmentCollection collection = client.GetRoleAssignments(new ResourceIdentifier(scope)); // invoke the operation string roleAssignmentName = "roleAssignmentName"; - RoleAssignmentCreateOrUpdateContent content = new RoleAssignmentCreateOrUpdateContent() + RoleAssignmentCreateOrUpdateContent content = new RoleAssignmentCreateOrUpdateContent { RoleDefinitionId = "/subscriptions/4004a9fd-d58e-48dc-aeb2-4a4aec58606f/providers/Microsoft.Authorization/roleDefinitions/de139f84-1756-47ae-9be6-808fbbe84772", PrincipalId = "d93a38bc-d029-4160-bfb0-fbda779ac214", @@ -68,13 +64,9 @@ public async Task Get_GetRoleAssignmentByName() // authenticate your client ArmClient client = new ArmClient(cred); - // this example assumes you already have this ArmResource created on azure - // for more information of creating ArmResource, please refer to the document of ArmResource - // get the collection of this RoleAssignmentResource string scope = "scope"; - ResourceIdentifier scopeId = new ResourceIdentifier(string.Format("/{0}", scope)); - RoleAssignmentCollection collection = client.GetRoleAssignments(scopeId); + RoleAssignmentCollection collection = client.GetRoleAssignments(new ResourceIdentifier(scope)); // invoke the operation string roleAssignmentName = "roleAssignmentName"; @@ -87,6 +79,35 @@ public async Task Get_GetRoleAssignmentByName() Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetAll_ListRoleAssignmentsForScope() + { + // Generated from example definition: + // this example is just showing the usage of "RoleAssignments_ListForScope" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // get the collection of this RoleAssignmentResource + string scope = "scope"; + RoleAssignmentCollection collection = client.GetRoleAssignments(new ResourceIdentifier(scope)); + + // invoke the operation and iterate over the result + await foreach (RoleAssignmentResource item in collection.GetAllAsync()) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + RoleAssignmentData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + + Console.WriteLine("Succeeded"); + } + [Test] [Ignore("Only validating compilation of examples")] public async Task Exists_GetRoleAssignmentByName() @@ -99,13 +120,9 @@ public async Task Exists_GetRoleAssignmentByName() // authenticate your client ArmClient client = new ArmClient(cred); - // this example assumes you already have this ArmResource created on azure - // for more information of creating ArmResource, please refer to the document of ArmResource - // get the collection of this RoleAssignmentResource string scope = "scope"; - ResourceIdentifier scopeId = new ResourceIdentifier(string.Format("/{0}", scope)); - RoleAssignmentCollection collection = client.GetRoleAssignments(scopeId); + RoleAssignmentCollection collection = client.GetRoleAssignments(new ResourceIdentifier(scope)); // invoke the operation string roleAssignmentName = "roleAssignmentName"; @@ -126,13 +143,9 @@ public async Task GetIfExists_GetRoleAssignmentByName() // authenticate your client ArmClient client = new ArmClient(cred); - // this example assumes you already have this ArmResource created on azure - // for more information of creating ArmResource, please refer to the document of ArmResource - // get the collection of this RoleAssignmentResource string scope = "scope"; - ResourceIdentifier scopeId = new ResourceIdentifier(string.Format("/{0}", scope)); - RoleAssignmentCollection collection = client.GetRoleAssignments(scopeId); + RoleAssignmentCollection collection = client.GetRoleAssignments(new ResourceIdentifier(scope)); // invoke the operation string roleAssignmentName = "roleAssignmentName"; @@ -152,38 +165,5 @@ public async Task GetIfExists_GetRoleAssignmentByName() Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task GetAll_ListRoleAssignmentsForScope() - { - // Generated from example definition: - // this example is just showing the usage of "RoleAssignments_ListForScope" operation, for the dependent resources, they will have to be created separately. - - // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line - TokenCredential cred = new DefaultAzureCredential(); - // authenticate your client - ArmClient client = new ArmClient(cred); - - // this example assumes you already have this ArmResource created on azure - // for more information of creating ArmResource, please refer to the document of ArmResource - - // get the collection of this RoleAssignmentResource - string scope = "scope"; - ResourceIdentifier scopeId = new ResourceIdentifier(string.Format("/{0}", scope)); - RoleAssignmentCollection collection = client.GetRoleAssignments(scopeId); - - // invoke the operation and iterate over the result - await foreach (RoleAssignmentResource item in collection.GetAllAsync()) - { - // the variable item is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - RoleAssignmentData resourceData = item.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } - - Console.WriteLine("Succeeded"); - } } } diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_RoleAssignmentResource.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_RoleAssignmentResource.cs index 2c1acdaa7ff..d871dc4eb21 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_RoleAssignmentResource.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_RoleAssignmentResource.cs @@ -20,10 +20,10 @@ public partial class Sample_RoleAssignmentResource { [Test] [Ignore("Only validating compilation of examples")] - public async Task Delete_DeleteRoleAssignmentByName() + public async Task Get_GetRoleAssignmentByName() { // Generated from example definition: - // this example is just showing the usage of "RoleAssignments_Delete" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "RoleAssignments_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -38,8 +38,7 @@ public async Task Delete_DeleteRoleAssignmentByName() RoleAssignmentResource roleAssignment = client.GetRoleAssignmentResource(roleAssignmentResourceId); // invoke the operation - ArmOperation lro = await roleAssignment.DeleteAsync(WaitUntil.Completed); - RoleAssignmentResource result = lro.Value; + RoleAssignmentResource result = await roleAssignment.GetAsync(); // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance @@ -50,10 +49,10 @@ public async Task Delete_DeleteRoleAssignmentByName() [Test] [Ignore("Only validating compilation of examples")] - public async Task Update_CreateRoleAssignment() + public async Task Delete_DeleteRoleAssignmentByName() { // Generated from example definition: - // this example is just showing the usage of "RoleAssignments_Create" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "RoleAssignments_Delete" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -68,13 +67,7 @@ public async Task Update_CreateRoleAssignment() RoleAssignmentResource roleAssignment = client.GetRoleAssignmentResource(roleAssignmentResourceId); // invoke the operation - RoleAssignmentCreateOrUpdateContent content = new RoleAssignmentCreateOrUpdateContent() - { - RoleDefinitionId = "/subscriptions/4004a9fd-d58e-48dc-aeb2-4a4aec58606f/providers/Microsoft.Authorization/roleDefinitions/de139f84-1756-47ae-9be6-808fbbe84772", - PrincipalId = "d93a38bc-d029-4160-bfb0-fbda779ac214", - CanDelegate = false, - }; - ArmOperation lro = await roleAssignment.UpdateAsync(WaitUntil.Completed, content); + ArmOperation lro = await roleAssignment.DeleteAsync(WaitUntil.Completed); RoleAssignmentResource result = lro.Value; // the variable result is a resource, you could call other operations on this instance as well @@ -86,10 +79,10 @@ public async Task Update_CreateRoleAssignment() [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetRoleAssignmentByName() + public async Task Update_CreateRoleAssignment() { // Generated from example definition: - // this example is just showing the usage of "RoleAssignments_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "RoleAssignments_Create" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -104,7 +97,14 @@ public async Task Get_GetRoleAssignmentByName() RoleAssignmentResource roleAssignment = client.GetRoleAssignmentResource(roleAssignmentResourceId); // invoke the operation - RoleAssignmentResource result = await roleAssignment.GetAsync(); + RoleAssignmentCreateOrUpdateContent content = new RoleAssignmentCreateOrUpdateContent + { + RoleDefinitionId = "/subscriptions/4004a9fd-d58e-48dc-aeb2-4a4aec58606f/providers/Microsoft.Authorization/roleDefinitions/de139f84-1756-47ae-9be6-808fbbe84772", + PrincipalId = "d93a38bc-d029-4160-bfb0-fbda779ac214", + CanDelegate = false, + }; + ArmOperation lro = await roleAssignment.UpdateAsync(WaitUntil.Completed, content); + RoleAssignmentResource result = lro.Value; // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_SubscriptionResourceExtensions.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_SubscriptionResourceExtensions.cs index e8a34db06e2..bf9b043c6cf 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_SubscriptionResourceExtensions.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_SubscriptionResourceExtensions.cs @@ -11,12 +11,45 @@ using Azure.Identity; using Azure.ResourceManager; using Azure.ResourceManager.Resources; +using MgmtMockAndSample.Models; using NUnit.Framework; namespace MgmtMockAndSample.Samples { public partial class Sample_SubscriptionResourceExtensions { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetVaults_ListVaultsInTheSpecifiedSubscription() + { + // Generated from example definition: + // this example is just showing the usage of "Vaults_ListBySubscription" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this SubscriptionResource created on azure + // for more information of creating SubscriptionResource, please refer to the document of SubscriptionResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + ResourceIdentifier subscriptionResourceId = SubscriptionResource.CreateResourceIdentifier(subscriptionId); + SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); + + // invoke the operation and iterate over the result + int? top = 1; + await foreach (VaultResource item in subscriptionResource.GetVaultsAsync(top: top)) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + VaultData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + + Console.WriteLine("Succeeded"); + } + [Test] [Ignore("Only validating compilation of examples")] public async Task GetDeletedVaults_ListDeletedVaultsInTheSpecifiedSubscription() @@ -48,6 +81,93 @@ public async Task GetDeletedVaults_ListDeletedVaultsInTheSpecifiedSubscription() Console.WriteLine("Succeeded"); } + [Test] + [Ignore("Only validating compilation of examples")] + public async Task CheckNameAvailabilityVault_ValidateAVaultName() + { + // Generated from example definition: + // this example is just showing the usage of "Vaults_CheckNameAvailability" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this SubscriptionResource created on azure + // for more information of creating SubscriptionResource, please refer to the document of SubscriptionResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + ResourceIdentifier subscriptionResourceId = SubscriptionResource.CreateResourceIdentifier(subscriptionId); + SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); + + // invoke the operation + VaultCheckNameAvailabilityContent content = new VaultCheckNameAvailabilityContent("sample-vault"); + CheckNameAvailabilityResult result = await subscriptionResource.CheckNameAvailabilityVaultAsync(content); + + Console.WriteLine($"Succeeded: {result}"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetDiskEncryptionSets_ListAllDiskEncryptionSetsInASubscription() + { + // Generated from example definition: + // this example is just showing the usage of "DiskEncryptionSets_List" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this SubscriptionResource created on azure + // for more information of creating SubscriptionResource, please refer to the document of SubscriptionResource + string subscriptionId = "{subscription-id}"; + ResourceIdentifier subscriptionResourceId = SubscriptionResource.CreateResourceIdentifier(subscriptionId); + SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); + + // invoke the operation and iterate over the result + await foreach (DiskEncryptionSetResource item in subscriptionResource.GetDiskEncryptionSetsAsync()) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + DiskEncryptionSetData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + + Console.WriteLine("Succeeded"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetManagedHsms_ListManagedHSMPoolsInASubscription() + { + // Generated from example definition: + // this example is just showing the usage of "ManagedHsms_ListBySubscription" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this SubscriptionResource created on azure + // for more information of creating SubscriptionResource, please refer to the document of SubscriptionResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + ResourceIdentifier subscriptionResourceId = SubscriptionResource.CreateResourceIdentifier(subscriptionId); + SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); + + // invoke the operation and iterate over the result + await foreach (ManagedHsmResource item in subscriptionResource.GetManagedHsmsAsync()) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + ManagedHsmData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + + Console.WriteLine("Succeeded"); + } + [Test] [Ignore("Only validating compilation of examples")] public async Task GetDeletedManagedHsms_ListDeletedManagedHSMsInTheSpecifiedSubscription() @@ -78,5 +198,36 @@ public async Task GetDeletedManagedHsms_ListDeletedManagedHSMsInTheSpecifiedSubs Console.WriteLine("Succeeded"); } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetFirewallPolicies_ListAllFirewallPoliciesForAGivenSubscription() + { + // Generated from example definition: + // this example is just showing the usage of "FirewallPolicies_ListAll" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this SubscriptionResource created on azure + // for more information of creating SubscriptionResource, please refer to the document of SubscriptionResource + string subscriptionId = "subid"; + ResourceIdentifier subscriptionResourceId = SubscriptionResource.CreateResourceIdentifier(subscriptionId); + SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); + + // invoke the operation and iterate over the result + await foreach (FirewallPolicyResource item in subscriptionResource.GetFirewallPoliciesAsync()) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + FirewallPolicyData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + + Console.WriteLine("Succeeded"); + } } } diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_TenantResourceExtensions.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_TenantResourceExtensions.cs index a8ae76bbcaa..1af0541d05f 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_TenantResourceExtensions.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_TenantResourceExtensions.cs @@ -11,6 +11,7 @@ using Azure.Core; using Azure.Identity; using Azure.ResourceManager; +using Azure.ResourceManager.Resources; using MgmtMockAndSample.Models; using NUnit.Framework; @@ -30,9 +31,7 @@ public async Task GetTenantActivityLogs_GetTenantActivityLogsWithoutFilterOrSele // authenticate your client ArmClient client = new ArmClient(cred); - // this example assumes you already have this TenantResource created on azure - // for more information of creating TenantResource, please refer to the document of TenantResource - var tenantResource = client.GetTenants().GetAllAsync().GetAsyncEnumerator().Current; + TenantResource tenantResource = client.GetTenants().GetAllAsync().GetAsyncEnumerator().Current; // invoke the operation and iterate over the result await foreach (EventData item in tenantResource.GetTenantActivityLogsAsync()) @@ -55,48 +54,52 @@ public async Task CalculateTemplateHashDeployment_CalculateTemplateHash() // authenticate your client ArmClient client = new ArmClient(cred); - // this example assumes you already have this TenantResource created on azure - // for more information of creating TenantResource, please refer to the document of TenantResource - var tenantResource = client.GetTenants().GetAllAsync().GetAsyncEnumerator().Current; + TenantResource tenantResource = client.GetTenants().GetAllAsync().GetAsyncEnumerator().Current; // invoke the operation - TenantResourceCalculateTemplateHashDeploymentOptions options = new TenantResourceCalculateTemplateHashDeploymentOptions(template: BinaryData.FromObjectAsJson(new Dictionary() + BinaryData template = BinaryData.FromObjectAsJson(new Dictionary { ["$schema"] = "http://schemas.management.azure.com/deploymentTemplate?api-version=2014-04-01-preview", ["contentVersion"] = "1.0.0.0", - ["outputs"] = new Dictionary() + ["outputs"] = new Dictionary { - ["string"] = new Dictionary() + ["string"] = new { - ["type"] = "string", - ["value"] = "myvalue" + type = "string", + value = "myvalue", } }, - ["parameters"] = new Dictionary() + ["parameters"] = new Dictionary { - ["string"] = new Dictionary() + ["string"] = new { - ["type"] = "string" + type = "string", } }, - ["resources"] = new object[] { }, - ["variables"] = new Dictionary() + ["resources"] = Array.Empty(), + ["variables"] = new Dictionary { - ["array"] = new object[] { "1", "2", "3", "4" }, + ["array"] = new object[] + { +"1", +"2", +"3", +"4" + }, ["bool"] = "true", ["int"] = "42", - ["object"] = new Dictionary() + ["object"] = new Dictionary { - ["object"] = new Dictionary() + ["object"] = new { - ["location"] = "West US", - ["vmSize"] = "Large" + location = "West US", + vmSize = "Large", } }, ["string"] = "string" } - })) - { }; + }); + TenantResourceCalculateTemplateHashDeploymentOptions options = new TenantResourceCalculateTemplateHashDeploymentOptions(template); TemplateHashResult result = await tenantResource.CalculateTemplateHashDeploymentAsync(options); Console.WriteLine($"Succeeded: {result}"); @@ -114,48 +117,52 @@ public async Task CalculateTemplateHashDeployment_CalculateTemplateHashWithQuery // authenticate your client ArmClient client = new ArmClient(cred); - // this example assumes you already have this TenantResource created on azure - // for more information of creating TenantResource, please refer to the document of TenantResource - var tenantResource = client.GetTenants().GetAllAsync().GetAsyncEnumerator().Current; + TenantResource tenantResource = client.GetTenants().GetAllAsync().GetAsyncEnumerator().Current; // invoke the operation - TenantResourceCalculateTemplateHashDeploymentOptions options = new TenantResourceCalculateTemplateHashDeploymentOptions(template: BinaryData.FromObjectAsJson(new Dictionary() + BinaryData template = BinaryData.FromObjectAsJson(new Dictionary { ["$schema"] = "http://schemas.management.azure.com/deploymentTemplate?api-version=2014-04-01-preview", ["contentVersion"] = "1.0.0.0", - ["outputs"] = new Dictionary() + ["outputs"] = new Dictionary { - ["string"] = new Dictionary() + ["string"] = new { - ["type"] = "string", - ["value"] = "myvalue" + type = "string", + value = "myvalue", } }, - ["parameters"] = new Dictionary() + ["parameters"] = new Dictionary { - ["string"] = new Dictionary() + ["string"] = new { - ["type"] = "string" + type = "string", } }, - ["resources"] = new object[] { }, - ["variables"] = new Dictionary() + ["resources"] = Array.Empty(), + ["variables"] = new Dictionary { - ["array"] = new object[] { "1", "2", "3", "4" }, + ["array"] = new object[] + { +"1", +"2", +"3", +"4" + }, ["bool"] = "true", ["int"] = "42", - ["object"] = new Dictionary() + ["object"] = new Dictionary { - ["object"] = new Dictionary() + ["object"] = new { - ["location"] = "West US", - ["vmSize"] = "Large" + location = "West US", + vmSize = "Large", } }, ["string"] = "string" } - })) - { Q1 = "first", Q2 = 42, Q3 = 0L, Q4 = (float)3.14, Q5 = 3.14159265358, Q6 = true }; + }); + TenantResourceCalculateTemplateHashDeploymentOptions options = new TenantResourceCalculateTemplateHashDeploymentOptions(template) { Q1 = "first", Q2 = 42, Q3 = 0L, Q4 = (float)3.14, Q5 = 3.14159265358, Q6 = true }; TemplateHashResult result = await tenantResource.CalculateTemplateHashDeploymentAsync(options); Console.WriteLine($"Succeeded: {result}"); diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_VaultCollection.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_VaultCollection.cs index a50a3381d2d..e23229bbc44 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_VaultCollection.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_VaultCollection.cs @@ -49,24 +49,12 @@ public async Task CreateOrUpdate_CreateANewVaultOrUpdateAnExistingVault() { Duration = XmlConvert.ToTimeSpan("P7D"), CreateOn = DateTimeOffset.Parse("2017-05-04T07:12:28.191Z"), - AccessPolicies = + AccessPolicies = {new AccessPolicyEntry(Guid.Parse("00000000-0000-0000-0000-000000000000"), "00000000-0000-0000-0000-000000000000", new Permissions { -new AccessPolicyEntry(Guid.Parse("00000000-0000-0000-0000-000000000000"),"00000000-0000-0000-0000-000000000000",new Permissions() -{ -Keys = -{ -KeyPermission.Encrypt,KeyPermission.Decrypt,KeyPermission.WrapKey,KeyPermission.UnwrapKey,KeyPermission.Sign,KeyPermission.Verify,KeyPermission.Get,KeyPermission.List,KeyPermission.Create,KeyPermission.Update,KeyPermission.Import,KeyPermission.Delete,KeyPermission.Backup,KeyPermission.Restore,KeyPermission.Recover,KeyPermission.Purge -}, -Secrets = -{ -SecretPermission.Get,SecretPermission.List,SecretPermission.Set,SecretPermission.Delete,SecretPermission.Backup,SecretPermission.Restore,SecretPermission.Recover,SecretPermission.Purge -}, -Certificates = -{ -CertificatePermission.Get,CertificatePermission.List,CertificatePermission.Delete,CertificatePermission.Create,CertificatePermission.Import,CertificatePermission.Update,CertificatePermission.Managecontacts,CertificatePermission.Getissuers,CertificatePermission.Listissuers,CertificatePermission.Setissuers,CertificatePermission.Deleteissuers,CertificatePermission.Manageissuers,CertificatePermission.Recover,CertificatePermission.Purge -}, -}) -}, +Keys = {KeyPermission.Encrypt, KeyPermission.Decrypt, KeyPermission.WrapKey, KeyPermission.UnwrapKey, KeyPermission.Sign, KeyPermission.Verify, KeyPermission.Get, KeyPermission.List, KeyPermission.Create, KeyPermission.Update, KeyPermission.Import, KeyPermission.Delete, KeyPermission.Backup, KeyPermission.Restore, KeyPermission.Recover, KeyPermission.Purge}, +Secrets = {SecretPermission.Get, SecretPermission.List, SecretPermission.Set, SecretPermission.Delete, SecretPermission.Backup, SecretPermission.Restore, SecretPermission.Recover, SecretPermission.Purge}, +Certificates = {CertificatePermission.Get, CertificatePermission.List, CertificatePermission.Delete, CertificatePermission.Create, CertificatePermission.Import, CertificatePermission.Update, CertificatePermission.Managecontacts, CertificatePermission.Getissuers, CertificatePermission.Listissuers, CertificatePermission.Setissuers, CertificatePermission.Deleteissuers, CertificatePermission.Manageissuers, CertificatePermission.Recover, CertificatePermission.Purge}, +})}, EnabledForDiskEncryption = true, EnabledForTemplateDeployment = true, PublicNetworkAccess = "Enabled", @@ -112,18 +100,12 @@ public async Task CreateOrUpdate_CreateOrUpdateAVaultWithNetworkAcls() { EnabledForDiskEncryption = true, EnabledForTemplateDeployment = true, - NetworkAcls = new NetworkRuleSet() + NetworkAcls = new NetworkRuleSet { Bypass = NetworkRuleBypassOption.AzureServices, DefaultAction = NetworkRuleAction.Deny, - IpRules = -{ -new IPRule("124.56.78.91"),new IPRule("'10.91.4.0/24'") -}, - VirtualNetworkRules = -{ -new VirtualNetworkRule("/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1") -}, + IpRules = { new IPRule("124.56.78.91"), new IPRule("'10.91.4.0/24'") }, + VirtualNetworkRules = { new VirtualNetworkRule("/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1") }, }, ReadWriteSingleStringPropertySomething = "test", DeepSomething = "deep-value", @@ -161,29 +143,17 @@ public async Task CreateOrUpdate_VerifySampleGenCanHandleExamplesWithSomeParamet VaultCollection collection = resourceGroupResource.GetVaults(); // invoke the operation - string vaultName = default /* Warning: No value is provided for vaultName in example 'Verify Sample-gen can handle examples with some parameter missing'. Please consider adding a proper example value for it in swagger*/; + string vaultName = null; VaultCreateOrUpdateContent content = new VaultCreateOrUpdateContent(new AzureLocation("westus"), new VaultProperties(Guid.Parse("00000000-0000-0000-0000-000000000000"), new MgmtMockAndSampleSku(MgmtMockAndSampleSkuFamily.A, MgmtMockAndSampleSkuName.Standard)) { Duration = XmlConvert.ToTimeSpan("P7D"), CreateOn = DateTimeOffset.Parse("2017-05-04T07:12:28.191Z"), - AccessPolicies = -{ -new AccessPolicyEntry(Guid.Parse("00000000-0000-0000-0000-000000000000"),"00000000-0000-0000-0000-000000000000",new Permissions() -{ -Keys = -{ -KeyPermission.Encrypt,KeyPermission.Decrypt,KeyPermission.WrapKey,KeyPermission.UnwrapKey,KeyPermission.Sign,KeyPermission.Verify,KeyPermission.Get,KeyPermission.List,KeyPermission.Create,KeyPermission.Update,KeyPermission.Import,KeyPermission.Delete,KeyPermission.Backup,KeyPermission.Restore,KeyPermission.Recover,KeyPermission.Purge -}, -Secrets = -{ -SecretPermission.Get,SecretPermission.List,SecretPermission.Set,SecretPermission.Delete,SecretPermission.Backup,SecretPermission.Restore,SecretPermission.Recover,SecretPermission.Purge -}, -Certificates = + AccessPolicies = {new AccessPolicyEntry(Guid.Parse("00000000-0000-0000-0000-000000000000"), "00000000-0000-0000-0000-000000000000", new Permissions { -CertificatePermission.Get,CertificatePermission.List,CertificatePermission.Delete,CertificatePermission.Create,CertificatePermission.Import,CertificatePermission.Update,CertificatePermission.Managecontacts,CertificatePermission.Getissuers,CertificatePermission.Listissuers,CertificatePermission.Setissuers,CertificatePermission.Deleteissuers,CertificatePermission.Manageissuers,CertificatePermission.Recover,CertificatePermission.Purge -}, -}) -}, +Keys = {KeyPermission.Encrypt, KeyPermission.Decrypt, KeyPermission.WrapKey, KeyPermission.UnwrapKey, KeyPermission.Sign, KeyPermission.Verify, KeyPermission.Get, KeyPermission.List, KeyPermission.Create, KeyPermission.Update, KeyPermission.Import, KeyPermission.Delete, KeyPermission.Backup, KeyPermission.Restore, KeyPermission.Recover, KeyPermission.Purge}, +Secrets = {SecretPermission.Get, SecretPermission.List, SecretPermission.Set, SecretPermission.Delete, SecretPermission.Backup, SecretPermission.Restore, SecretPermission.Recover, SecretPermission.Purge}, +Certificates = {CertificatePermission.Get, CertificatePermission.List, CertificatePermission.Delete, CertificatePermission.Create, CertificatePermission.Import, CertificatePermission.Update, CertificatePermission.Managecontacts, CertificatePermission.Getissuers, CertificatePermission.Listissuers, CertificatePermission.Setissuers, CertificatePermission.Deleteissuers, CertificatePermission.Manageissuers, CertificatePermission.Recover, CertificatePermission.Purge}, +})}, EnabledForDiskEncryption = true, EnabledForTemplateDeployment = true, PublicNetworkAccess = "Enabled", @@ -236,10 +206,10 @@ public async Task Get_RetrieveAVault() [Test] [Ignore("Only validating compilation of examples")] - public async Task Exists_RetrieveAVault() + public async Task GetAll_ListVaultsInTheSpecifiedResourceGroup() { // Generated from example definition: - // this example is just showing the usage of "Vaults_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "Vaults_ListByResourceGroup" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -249,23 +219,30 @@ public async Task Exists_RetrieveAVault() // this example assumes you already have this ResourceGroupResource created on azure // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource string subscriptionId = "00000000-0000-0000-0000-000000000000"; - string resourceGroupName = "sample-resource-group"; + string resourceGroupName = "sample-group"; ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); // get the collection of this VaultResource VaultCollection collection = resourceGroupResource.GetVaults(); - // invoke the operation - string vaultName = "sample-vault"; - bool result = await collection.ExistsAsync(vaultName); + // invoke the operation and iterate over the result + int? top = 1; + await foreach (VaultResource item in collection.GetAllAsync(top: top)) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + VaultData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } - Console.WriteLine($"Succeeded: {result}"); + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetIfExists_RetrieveAVault() + public async Task Exists_RetrieveAVault() { // Generated from example definition: // this example is just showing the usage of "Vaults_Get" operation, for the dependent resources, they will have to be created separately. @@ -287,29 +264,17 @@ public async Task GetIfExists_RetrieveAVault() // invoke the operation string vaultName = "sample-vault"; - NullableResponse response = await collection.GetIfExistsAsync(vaultName); - VaultResource result = response.HasValue ? response.Value : null; + bool result = await collection.ExistsAsync(vaultName); - if (result == null) - { - Console.WriteLine("Succeeded with null as result"); - } - else - { - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - VaultData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } + Console.WriteLine($"Succeeded: {result}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetAll_ListVaultsInTheSpecifiedResourceGroup() + public async Task GetIfExists_RetrieveAVault() { // Generated from example definition: - // this example is just showing the usage of "Vaults_ListByResourceGroup" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "Vaults_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -319,25 +284,30 @@ public async Task GetAll_ListVaultsInTheSpecifiedResourceGroup() // this example assumes you already have this ResourceGroupResource created on azure // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource string subscriptionId = "00000000-0000-0000-0000-000000000000"; - string resourceGroupName = "sample-group"; + string resourceGroupName = "sample-resource-group"; ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); // get the collection of this VaultResource VaultCollection collection = resourceGroupResource.GetVaults(); - // invoke the operation and iterate over the result - int? top = 1; - await foreach (VaultResource item in collection.GetAllAsync(top: top)) + // invoke the operation + string vaultName = "sample-vault"; + NullableResponse response = await collection.GetIfExistsAsync(vaultName); + VaultResource result = response.HasValue ? response.Value : null; + + if (result == null) { - // the variable item is a resource, you could call other operations on this instance as well + Console.WriteLine("Succeeded with null as result"); + } + else + { + // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - VaultData resourceData = item.Data; + VaultData resourceData = result.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } - - Console.WriteLine("Succeeded"); } } } diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_VaultResource.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_VaultResource.cs index e61b495ecbd..b45a6fbabff 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_VaultResource.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_VaultResource.cs @@ -11,7 +11,6 @@ using Azure.Core; using Azure.Identity; using Azure.ResourceManager; -using Azure.ResourceManager.Resources; using MgmtMockAndSample.Models; using NUnit.Framework; @@ -21,10 +20,10 @@ public partial class Sample_VaultResource { [Test] [Ignore("Only validating compilation of examples")] - public async Task Delete_DeleteAVault() + public async Task Get_RetrieveAVault() { // Generated from example definition: - // this example is just showing the usage of "Vaults_Delete" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "Vaults_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -40,17 +39,21 @@ public async Task Delete_DeleteAVault() VaultResource vault = client.GetVaultResource(vaultResourceId); // invoke the operation - await vault.DeleteAsync(WaitUntil.Completed); + VaultResource result = await vault.GetAsync(); - Console.WriteLine("Succeeded"); + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + VaultData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_RetrieveAVault() + public async Task Delete_DeleteAVault() { // Generated from example definition: - // this example is just showing the usage of "Vaults_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "Vaults_Delete" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -66,13 +69,9 @@ public async Task Get_RetrieveAVault() VaultResource vault = client.GetVaultResource(vaultResourceId); // invoke the operation - VaultResource result = await vault.GetAsync(); + await vault.DeleteAsync(WaitUntil.Completed); - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - VaultData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + Console.WriteLine("Succeeded"); } [Test] @@ -180,20 +179,11 @@ public async Task UpdateAccessPolicy_AddAnAccessPolicyOrUpdateAnAccessPolicyWith AccessPolicyUpdateKind operationKind = AccessPolicyUpdateKind.Add; VaultAccessPolicyParameters vaultAccessPolicyParameters = new VaultAccessPolicyParameters(new VaultAccessPolicyProperties(new AccessPolicyEntry[] { -new AccessPolicyEntry(Guid.Parse("00000000-0000-0000-0000-000000000000"),"00000000-0000-0000-0000-000000000000",new Permissions() +new AccessPolicyEntry(Guid.Parse("00000000-0000-0000-0000-000000000000"), "00000000-0000-0000-0000-000000000000", new Permissions { -Keys = -{ -KeyPermission.Encrypt -}, -Secrets = -{ -SecretPermission.Get -}, -Certificates = -{ -CertificatePermission.Get -}, +Keys = {KeyPermission.Encrypt}, +Secrets = {SecretPermission.Get}, +Certificates = {CertificatePermission.Get}, }) })); VaultAccessPolicyParameters result = await vault.UpdateAccessPolicyAsync(operationKind, vaultAccessPolicyParameters); @@ -201,63 +191,6 @@ public async Task UpdateAccessPolicy_AddAnAccessPolicyOrUpdateAnAccessPolicyWith Console.WriteLine($"Succeeded: {result}"); } - [Test] - [Ignore("Only validating compilation of examples")] - public async Task GetVaults_ListVaultsInTheSpecifiedSubscription() - { - // Generated from example definition: - // this example is just showing the usage of "Vaults_ListBySubscription" operation, for the dependent resources, they will have to be created separately. - - // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line - TokenCredential cred = new DefaultAzureCredential(); - // authenticate your client - ArmClient client = new ArmClient(cred); - - // this example assumes you already have this SubscriptionResource created on azure - // for more information of creating SubscriptionResource, please refer to the document of SubscriptionResource - string subscriptionId = "00000000-0000-0000-0000-000000000000"; - ResourceIdentifier subscriptionResourceId = SubscriptionResource.CreateResourceIdentifier(subscriptionId); - SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); - - // invoke the operation and iterate over the result - int? top = 1; - await foreach (VaultResource item in subscriptionResource.GetVaultsAsync(top: top)) - { - // the variable item is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - VaultData resourceData = item.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } - - Console.WriteLine("Succeeded"); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task CheckNameAvailabilityVault_ValidateAVaultName() - { - // Generated from example definition: - // this example is just showing the usage of "Vaults_CheckNameAvailability" operation, for the dependent resources, they will have to be created separately. - - // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line - TokenCredential cred = new DefaultAzureCredential(); - // authenticate your client - ArmClient client = new ArmClient(cred); - - // this example assumes you already have this SubscriptionResource created on azure - // for more information of creating SubscriptionResource, please refer to the document of SubscriptionResource - string subscriptionId = "00000000-0000-0000-0000-000000000000"; - ResourceIdentifier subscriptionResourceId = SubscriptionResource.CreateResourceIdentifier(subscriptionId); - SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); - - // invoke the operation - VaultCheckNameAvailabilityContent content = new VaultCheckNameAvailabilityContent("sample-vault"); - CheckNameAvailabilityResult result = await subscriptionResource.CheckNameAvailabilityVaultAsync(content); - - Console.WriteLine($"Succeeded: {result}"); - } - [Test] [Ignore("Only validating compilation of examples")] public async Task GetPrivateLinkResources_KeyVaultListPrivateLinkResources() diff --git a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_VirtualMachineExtensionImageCollection.cs b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_VirtualMachineExtensionImageCollection.cs index 88ff6c82fef..0f7986ac234 100644 --- a/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_VirtualMachineExtensionImageCollection.cs +++ b/test/TestProjects/MgmtMockAndSample/tests/Generated/Samples/Sample_VirtualMachineExtensionImageCollection.cs @@ -55,7 +55,7 @@ public async Task Get_VirtualMachineExtensionImagesGetMaximumSetGen() [Test] [Ignore("Only validating compilation of examples")] - public async Task Exists_VirtualMachineExtensionImagesGetMaximumSetGen() + public async Task Get_VirtualMachineExtensionImagesGetMinimumSetGen() { // Generated from example definition: // this example is just showing the usage of "VirtualMachineExtensionImages_Get" operation, for the dependent resources, they will have to be created separately. @@ -72,24 +72,28 @@ public async Task Exists_VirtualMachineExtensionImagesGetMaximumSetGen() SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); // get the collection of this VirtualMachineExtensionImageResource - AzureLocation location = new AzureLocation("aaaaaaaaaaaaa"); - string publisherName = "aaaaaaaaaaaaaaaaaaaa"; + AzureLocation location = new AzureLocation("aaaaaaaaaaaaaa"); + string publisherName = "aaaaaaaaaaaaaaaaaaaaaaaaaa"; VirtualMachineExtensionImageCollection collection = subscriptionResource.GetVirtualMachineExtensionImages(location, publisherName); // invoke the operation - string type = "aaaaaaaaaaaaaaaaaa"; - string version = "aaaaaaaaaaaaaa"; - bool result = await collection.ExistsAsync(type, version); + string type = "aa"; + string version = "aaa"; + VirtualMachineExtensionImageResource result = await collection.GetAsync(type, version); - Console.WriteLine($"Succeeded: {result}"); + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + VirtualMachineExtensionImageData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetIfExists_VirtualMachineExtensionImagesGetMaximumSetGen() + public async Task GetAll_VirtualMachineExtensionImagesListTypesMaximumSetGen() { // Generated from example definition: - // this example is just showing the usage of "VirtualMachineExtensionImages_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "VirtualMachineExtensionImages_ListTypes" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -103,36 +107,29 @@ public async Task GetIfExists_VirtualMachineExtensionImagesGetMaximumSetGen() SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); // get the collection of this VirtualMachineExtensionImageResource - AzureLocation location = new AzureLocation("aaaaaaaaaaaaa"); - string publisherName = "aaaaaaaaaaaaaaaaaaaa"; + AzureLocation location = new AzureLocation("aaaaaaaaaaaaaaaaaaaaaaaaaa"); + string publisherName = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; VirtualMachineExtensionImageCollection collection = subscriptionResource.GetVirtualMachineExtensionImages(location, publisherName); - // invoke the operation - string type = "aaaaaaaaaaaaaaaaaa"; - string version = "aaaaaaaaaaaaaa"; - NullableResponse response = await collection.GetIfExistsAsync(type, version); - VirtualMachineExtensionImageResource result = response.HasValue ? response.Value : null; - - if (result == null) - { - Console.WriteLine("Succeeded with null as result"); - } - else + // invoke the operation and iterate over the result + await foreach (VirtualMachineExtensionImageResource item in collection.GetAllAsync()) { - // the variable result is a resource, you could call other operations on this instance as well + // the variable item is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - VirtualMachineExtensionImageData resourceData = result.Data; + VirtualMachineExtensionImageData resourceData = item.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } + + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_VirtualMachineExtensionImagesGetMinimumSetGen() + public async Task GetAll_VirtualMachineExtensionImagesListTypesMinimumSetGen() { // Generated from example definition: - // this example is just showing the usage of "VirtualMachineExtensionImages_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "VirtualMachineExtensionImages_ListTypes" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -146,28 +143,29 @@ public async Task Get_VirtualMachineExtensionImagesGetMinimumSetGen() SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); // get the collection of this VirtualMachineExtensionImageResource - AzureLocation location = new AzureLocation("aaaaaaaaaaaaaa"); - string publisherName = "aaaaaaaaaaaaaaaaaaaaaaaaaa"; + AzureLocation location = new AzureLocation("aaaa"); + string publisherName = "aa"; VirtualMachineExtensionImageCollection collection = subscriptionResource.GetVirtualMachineExtensionImages(location, publisherName); - // invoke the operation - string type = "aa"; - string version = "aaa"; - VirtualMachineExtensionImageResource result = await collection.GetAsync(type, version); + // invoke the operation and iterate over the result + await foreach (VirtualMachineExtensionImageResource item in collection.GetAllAsync()) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + VirtualMachineExtensionImageData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } - // the variable result is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - VirtualMachineExtensionImageData resourceData = result.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Exists_VirtualMachineExtensionImagesGetMinimumSetGen() + public async Task GetAll_VirtualMachineExtensionImagesListVersionsMaximumSetGen() { // Generated from example definition: - // this example is just showing the usage of "VirtualMachineExtensionImages_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "VirtualMachineExtensionImages_ListVersions" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -181,24 +179,33 @@ public async Task Exists_VirtualMachineExtensionImagesGetMinimumSetGen() SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); // get the collection of this VirtualMachineExtensionImageResource - AzureLocation location = new AzureLocation("aaaaaaaaaaaaaa"); - string publisherName = "aaaaaaaaaaaaaaaaaaaaaaaaaa"; + AzureLocation location = new AzureLocation("aaaaaaaaaaaaaaaaaaaaaaaaaa"); + string publisherName = "aaaaaaaaaaaaaaaaaaaa"; VirtualMachineExtensionImageCollection collection = subscriptionResource.GetVirtualMachineExtensionImages(location, publisherName); - // invoke the operation - string type = "aa"; - string version = "aaa"; - bool result = await collection.ExistsAsync(type, version); + // invoke the operation and iterate over the result + string type = "aaaaaaaaaaaaaaaaaa"; + string filter = "aaaaaaaaaaaaaaaaaaaaaaaaa"; + int? top = 22; + string orderby = "a"; + await foreach (VirtualMachineExtensionImageResource item in collection.GetAllAsync(type, filter: filter, top: top, orderby: orderby)) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + VirtualMachineExtensionImageData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } - Console.WriteLine($"Succeeded: {result}"); + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetIfExists_VirtualMachineExtensionImagesGetMinimumSetGen() + public async Task GetAll_VirtualMachineExtensionImagesListVersionsMinimumSetGen() { // Generated from example definition: - // this example is just showing the usage of "VirtualMachineExtensionImages_Get" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "VirtualMachineExtensionImages_ListVersions" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -212,36 +219,30 @@ public async Task GetIfExists_VirtualMachineExtensionImagesGetMinimumSetGen() SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); // get the collection of this VirtualMachineExtensionImageResource - AzureLocation location = new AzureLocation("aaaaaaaaaaaaaa"); - string publisherName = "aaaaaaaaaaaaaaaaaaaaaaaaaa"; + AzureLocation location = new AzureLocation("aaaaaaaaa"); + string publisherName = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; VirtualMachineExtensionImageCollection collection = subscriptionResource.GetVirtualMachineExtensionImages(location, publisherName); - // invoke the operation - string type = "aa"; - string version = "aaa"; - NullableResponse response = await collection.GetIfExistsAsync(type, version); - VirtualMachineExtensionImageResource result = response.HasValue ? response.Value : null; - - if (result == null) - { - Console.WriteLine("Succeeded with null as result"); - } - else + // invoke the operation and iterate over the result + string type = "aaaa"; + await foreach (VirtualMachineExtensionImageResource item in collection.GetAllAsync(type)) { - // the variable result is a resource, you could call other operations on this instance as well + // the variable item is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - VirtualMachineExtensionImageData resourceData = result.Data; + VirtualMachineExtensionImageData resourceData = item.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } + + Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetAll_VirtualMachineExtensionImagesListTypesMaximumSetGen() + public async Task Exists_VirtualMachineExtensionImagesGetMaximumSetGen() { // Generated from example definition: - // this example is just showing the usage of "VirtualMachineExtensionImages_ListTypes" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "VirtualMachineExtensionImages_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -255,29 +256,24 @@ public async Task GetAll_VirtualMachineExtensionImagesListTypesMaximumSetGen() SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); // get the collection of this VirtualMachineExtensionImageResource - AzureLocation location = new AzureLocation("aaaaaaaaaaaaaaaaaaaaaaaaaa"); - string publisherName = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + AzureLocation location = new AzureLocation("aaaaaaaaaaaaa"); + string publisherName = "aaaaaaaaaaaaaaaaaaaa"; VirtualMachineExtensionImageCollection collection = subscriptionResource.GetVirtualMachineExtensionImages(location, publisherName); - // invoke the operation and iterate over the result - await foreach (VirtualMachineExtensionImageResource item in collection.GetAllAsync()) - { - // the variable item is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - VirtualMachineExtensionImageData resourceData = item.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } + // invoke the operation + string type = "aaaaaaaaaaaaaaaaaa"; + string version = "aaaaaaaaaaaaaa"; + bool result = await collection.ExistsAsync(type, version); - Console.WriteLine("Succeeded"); + Console.WriteLine($"Succeeded: {result}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetAll_VirtualMachineExtensionImagesListTypesMinimumSetGen() + public async Task Exists_VirtualMachineExtensionImagesGetMinimumSetGen() { // Generated from example definition: - // this example is just showing the usage of "VirtualMachineExtensionImages_ListTypes" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "VirtualMachineExtensionImages_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -291,29 +287,24 @@ public async Task GetAll_VirtualMachineExtensionImagesListTypesMinimumSetGen() SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); // get the collection of this VirtualMachineExtensionImageResource - AzureLocation location = new AzureLocation("aaaa"); - string publisherName = "aa"; + AzureLocation location = new AzureLocation("aaaaaaaaaaaaaa"); + string publisherName = "aaaaaaaaaaaaaaaaaaaaaaaaaa"; VirtualMachineExtensionImageCollection collection = subscriptionResource.GetVirtualMachineExtensionImages(location, publisherName); - // invoke the operation and iterate over the result - await foreach (VirtualMachineExtensionImageResource item in collection.GetAllAsync()) - { - // the variable item is a resource, you could call other operations on this instance as well - // but just for demo, we get its data from this resource instance - VirtualMachineExtensionImageData resourceData = item.Data; - // for demo we just print out the id - Console.WriteLine($"Succeeded on id: {resourceData.Id}"); - } + // invoke the operation + string type = "aa"; + string version = "aaa"; + bool result = await collection.ExistsAsync(type, version); - Console.WriteLine("Succeeded"); + Console.WriteLine($"Succeeded: {result}"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetAll_VirtualMachineExtensionImagesListVersionsMaximumSetGen() + public async Task GetIfExists_VirtualMachineExtensionImagesGetMaximumSetGen() { // Generated from example definition: - // this example is just showing the usage of "VirtualMachineExtensionImages_ListVersions" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "VirtualMachineExtensionImages_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -327,33 +318,36 @@ public async Task GetAll_VirtualMachineExtensionImagesListVersionsMaximumSetGen( SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); // get the collection of this VirtualMachineExtensionImageResource - AzureLocation location = new AzureLocation("aaaaaaaaaaaaaaaaaaaaaaaaaa"); + AzureLocation location = new AzureLocation("aaaaaaaaaaaaa"); string publisherName = "aaaaaaaaaaaaaaaaaaaa"; VirtualMachineExtensionImageCollection collection = subscriptionResource.GetVirtualMachineExtensionImages(location, publisherName); - // invoke the operation and iterate over the result + // invoke the operation string type = "aaaaaaaaaaaaaaaaaa"; - string filter = "aaaaaaaaaaaaaaaaaaaaaaaaa"; - int? top = 22; - string orderby = "a"; - await foreach (VirtualMachineExtensionImageResource item in collection.GetAllAsync(type, filter: filter, top: top, orderby: orderby)) + string version = "aaaaaaaaaaaaaa"; + NullableResponse response = await collection.GetIfExistsAsync(type, version); + VirtualMachineExtensionImageResource result = response.HasValue ? response.Value : null; + + if (result == null) { - // the variable item is a resource, you could call other operations on this instance as well + Console.WriteLine("Succeeded with null as result"); + } + else + { + // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - VirtualMachineExtensionImageData resourceData = item.Data; + VirtualMachineExtensionImageData resourceData = result.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } - - Console.WriteLine("Succeeded"); } [Test] [Ignore("Only validating compilation of examples")] - public async Task GetAll_VirtualMachineExtensionImagesListVersionsMinimumSetGen() + public async Task GetIfExists_VirtualMachineExtensionImagesGetMinimumSetGen() { // Generated from example definition: - // this example is just showing the usage of "VirtualMachineExtensionImages_ListVersions" operation, for the dependent resources, they will have to be created separately. + // this example is just showing the usage of "VirtualMachineExtensionImages_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -367,22 +361,28 @@ public async Task GetAll_VirtualMachineExtensionImagesListVersionsMinimumSetGen( SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); // get the collection of this VirtualMachineExtensionImageResource - AzureLocation location = new AzureLocation("aaaaaaaaa"); - string publisherName = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + AzureLocation location = new AzureLocation("aaaaaaaaaaaaaa"); + string publisherName = "aaaaaaaaaaaaaaaaaaaaaaaaaa"; VirtualMachineExtensionImageCollection collection = subscriptionResource.GetVirtualMachineExtensionImages(location, publisherName); - // invoke the operation and iterate over the result - string type = "aaaa"; - await foreach (VirtualMachineExtensionImageResource item in collection.GetAllAsync(type)) + // invoke the operation + string type = "aa"; + string version = "aaa"; + NullableResponse response = await collection.GetIfExistsAsync(type, version); + VirtualMachineExtensionImageResource result = response.HasValue ? response.Value : null; + + if (result == null) { - // the variable item is a resource, you could call other operations on this instance as well + Console.WriteLine("Succeeded with null as result"); + } + else + { + // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance - VirtualMachineExtensionImageData resourceData = item.Data; + VirtualMachineExtensionImageData resourceData = result.Data; // for demo we just print out the id Console.WriteLine($"Succeeded on id: {resourceData.Id}"); } - - Console.WriteLine("Succeeded"); } } } diff --git a/test/TestProjects/MgmtScopeResource/src/Generated/Configuration.json b/test/TestProjects/MgmtScopeResource/src/Generated/Configuration.json index d98740d1955..1505d1e0b41 100644 --- a/test/TestProjects/MgmtScopeResource/src/Generated/Configuration.json +++ b/test/TestProjects/MgmtScopeResource/src/Generated/Configuration.json @@ -53,6 +53,9 @@ "OverrideOperationName": { "ResourceLinks_ListAtSourceScope": "GetAll" }, + "RawParameterizedScopes": [ + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}" + ], "PatchInitializerCustomization": { "Deployment": { "Properties": "new DeploymentProperties(current.Properties.Mode.HasValue ? current.Properties.Mode.Value : DeploymentMode.Incremental)" diff --git a/test/TestProjects/MgmtTypeSpec/samples/Generated/Samples/Sample_FooCollection.cs b/test/TestProjects/MgmtTypeSpec/samples/Generated/Samples/Sample_FooCollection.cs index 86d3e21a605..75608938251 100644 --- a/test/TestProjects/MgmtTypeSpec/samples/Generated/Samples/Sample_FooCollection.cs +++ b/test/TestProjects/MgmtTypeSpec/samples/Generated/Samples/Sample_FooCollection.cs @@ -43,9 +43,9 @@ public async Task CreateOrUpdate_CreateAFoo() // invoke the operation string fooName = "myFoo"; - FooData data = new FooData(new AzureLocation("placeholder")) + FooData data = new FooData(default) { - Properties = new FooProperties() + Properties = new FooProperties { ServiceUri = new Uri("https://myService.com"), Something = "for test only", diff --git a/test/TestProjects/MgmtTypeSpec/samples/Generated/Samples/Sample_FooResource.cs b/test/TestProjects/MgmtTypeSpec/samples/Generated/Samples/Sample_FooResource.cs index ea24f2e4d32..8678efae440 100644 --- a/test/TestProjects/MgmtTypeSpec/samples/Generated/Samples/Sample_FooResource.cs +++ b/test/TestProjects/MgmtTypeSpec/samples/Generated/Samples/Sample_FooResource.cs @@ -20,10 +20,10 @@ public partial class Sample_FooResource { [Test] [Ignore("Only validating compilation of examples")] - public async Task Update_CreateAFoo() + public async Task Get_GetAFoo() { - // Generated from example definition: 2024-05-01/Foos_CreateOrUpdate.json - // this example is just showing the usage of "Foo_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. + // Generated from example definition: 2024-05-01/Foos_Get.json + // this example is just showing the usage of "Foo_Get" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -39,19 +39,7 @@ public async Task Update_CreateAFoo() FooResource foo = client.GetFooResource(fooResourceId); // invoke the operation - FooData data = new FooData(new AzureLocation("placeholder")) - { - Properties = new FooProperties() - { - ServiceUri = new Uri("https://myService.com"), - Something = "for test only", - BoolValue = true, - FloatValue = 1.2F, - DoubleValue = 1.2, - }, - }; - ArmOperation lro = await foo.UpdateAsync(WaitUntil.Completed, data); - FooResource result = lro.Value; + FooResource result = await foo.GetAsync(); // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance @@ -62,10 +50,10 @@ public async Task Update_CreateAFoo() [Test] [Ignore("Only validating compilation of examples")] - public async Task Get_GetAFoo() + public async Task Update_CreateAFoo() { - // Generated from example definition: 2024-05-01/Foos_Get.json - // this example is just showing the usage of "Foo_Get" operation, for the dependent resources, they will have to be created separately. + // Generated from example definition: 2024-05-01/Foos_CreateOrUpdate.json + // this example is just showing the usage of "Foo_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line TokenCredential cred = new DefaultAzureCredential(); @@ -81,7 +69,19 @@ public async Task Get_GetAFoo() FooResource foo = client.GetFooResource(fooResourceId); // invoke the operation - FooResource result = await foo.GetAsync(); + FooData data = new FooData(default) + { + Properties = new FooProperties + { + ServiceUri = new Uri("https://myService.com"), + Something = "for test only", + BoolValue = true, + FloatValue = 1.2F, + DoubleValue = 1.2, + }, + }; + ArmOperation lro = await foo.UpdateAsync(WaitUntil.Completed, data); + FooResource result = lro.Value; // the variable result is a resource, you could call other operations on this instance as well // but just for demo, we get its data from this resource instance