diff --git a/Packages.Data.props b/Packages.Data.props index 8a5ffc14fd3..931e6970b23 100644 --- a/Packages.Data.props +++ b/Packages.Data.props @@ -39,7 +39,5 @@ - - diff --git a/src/AutoRest.CSharp/AutoRest.CSharp.csproj b/src/AutoRest.CSharp/AutoRest.CSharp.csproj index 4f999d435b1..4571e41fc68 100644 --- a/src/AutoRest.CSharp/AutoRest.CSharp.csproj +++ b/src/AutoRest.CSharp/AutoRest.CSharp.csproj @@ -29,8 +29,6 @@ - - diff --git a/src/AutoRest.CSharp/Common/AutoRest/Plugins/CSharpGen.cs b/src/AutoRest.CSharp/Common/AutoRest/Plugins/CSharpGen.cs index 2abbad90bf6..68ef478c9a0 100644 --- a/src/AutoRest.CSharp/Common/AutoRest/Plugins/CSharpGen.cs +++ b/src/AutoRest.CSharp/Common/AutoRest/Plugins/CSharpGen.cs @@ -12,10 +12,7 @@ using AutoRest.CSharp.Input.Source; using AutoRest.CSharp.Mgmt.Report; using AutoRest.CSharp.Utilities; -using Microsoft.Build.Construction; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using NuGet.Configuration; namespace AutoRest.CSharp.AutoRest.Plugins { @@ -25,9 +22,10 @@ internal class CSharpGen : IPlugin public async Task ExecuteAsync(CodeModel codeModel) { ValidateConfiguration(); + Directory.CreateDirectory(Configuration.OutputFolder); var project = await GeneratedCodeWorkspace.Create(Configuration.AbsoluteProjectFolder, Configuration.OutputFolder, Configuration.SharedSourceFolders); - var sourceInputModel = new SourceInputModel(await project.GetCompilationAsync(), previousContract: await LoadBaselineContract()); + var sourceInputModel = new SourceInputModel(await project.GetCompilationAsync()); if (Configuration.Generation1ConvenienceClient) { @@ -56,37 +54,6 @@ public async Task ExecuteAsync(CodeModel codeModel) return project; } - private async Task LoadBaselineContract() - { - string fullPath; - string projectFilePath = Path.GetFullPath(Path.Combine(Configuration.AbsoluteProjectFolder, $"{Configuration.Namespace}.csproj")); - if (!File.Exists(projectFilePath)) - return null; - - var baselineVersion = ProjectRootElement.Open(projectFilePath).Properties.SingleOrDefault(p => p.Name == "ApiCompatVersion")?.Value; - - if (baselineVersion is not null) - { - var nugetGlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(new NullSettings()); - var nugetFolder = Path.Combine(nugetGlobalPackageFolder, Configuration.Namespace.ToLowerInvariant(), baselineVersion, "lib", "netstandard2.0"); - fullPath = Path.Combine(nugetFolder, $"{Configuration.Namespace}.dll"); - if (File.Exists(fullPath)) - { - return await GeneratedCodeWorkspace.CreatePreviousContractFromDll(Path.Combine(nugetFolder, $"{Configuration.Namespace}.xml"), fullPath).GetCompilationAsync(); - } - } - - // fallback for testing purpose - var baselinePath = Path.GetFullPath(Path.Combine(Configuration.AbsoluteProjectFolder, "..", "..", "BaselineContract", Configuration.Namespace)); - fullPath = Path.Combine(baselinePath, $"{Configuration.Namespace}.dll"); - if (File.Exists(fullPath)) - { - return await GeneratedCodeWorkspace.CreatePreviousContractFromDll(Path.Combine(baselinePath, $"{Configuration.Namespace}.xml"), fullPath).GetCompilationAsync(); - } - - return null; - } - private void GenerateMgmtReport(GeneratedCodeWorkspace project) { MgmtReport.Instance.TransformSection.ForEachTransform((t, usages) => diff --git a/src/AutoRest.CSharp/Common/AutoRest/Plugins/GeneratedCodeWorkspace.cs b/src/AutoRest.CSharp/Common/AutoRest/Plugins/GeneratedCodeWorkspace.cs index 95e290baedb..2e91b3785bc 100644 --- a/src/AutoRest.CSharp/Common/AutoRest/Plugins/GeneratedCodeWorkspace.cs +++ b/src/AutoRest.CSharp/Common/AutoRest/Plugins/GeneratedCodeWorkspace.cs @@ -253,18 +253,6 @@ public static GeneratedCodeWorkspace CreateExistingCodeProject(string outputDire return new GeneratedCodeWorkspace(project); } - public static GeneratedCodeWorkspace CreatePreviousContractFromDll(string xmlDocumentationpath, string dllPath) - { - var workspace = new AdhocWorkspace(); - Project project = workspace.AddProject("PreviousContract", LanguageNames.CSharp); - project = project - .AddMetadataReferences(AssemblyMetadataReferences) - .WithCompilationOptions(new CSharpCompilationOptions( - OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Disable)); - project = project.AddMetadataReference(MetadataReference.CreateFromFile(dllPath, documentation: XmlDocumentationProvider.CreateFromFile(xmlDocumentationpath))); - return new GeneratedCodeWorkspace(project); - } - private static Project CreateGeneratedCodeProject() { var workspace = new AdhocWorkspace(); diff --git a/src/AutoRest.CSharp/Common/Generation/Types/CSharpType.cs b/src/AutoRest.CSharp/Common/Generation/Types/CSharpType.cs index f94a3cf5ed6..ee3b977cd42 100644 --- a/src/AutoRest.CSharp/Common/Generation/Types/CSharpType.cs +++ b/src/AutoRest.CSharp/Common/Generation/Types/CSharpType.cs @@ -257,42 +257,5 @@ public bool TryCast([MaybeNullWhen(false)] out T provider) where T : TypeProv provider = this.Implementation as T; return provider != null; } - - /// - /// Check whether two CSharpType instances equal or not - /// This is not the same as left.Equals(right) because this function only checks the names - /// - /// - /// - /// - public bool EqualsByName(CSharpType? other) - { - if (ReferenceEquals(this, other)) - { - return true; - } - - if (other is null) - { - return false; - } - - if (Namespace != other.Namespace) - return false; - - if (Name != other.Name) - return false; - - if (Arguments.Length != other.Arguments.Length) - return false; - - for (int i = 0; i < Arguments.Length; i++) - { - if (!Arguments[i].EqualsByName(other.Arguments[i])) - return false; - } - - return true; - } } } diff --git a/src/AutoRest.CSharp/Common/Generation/Writers/CodeWriter.cs b/src/AutoRest.CSharp/Common/Generation/Writers/CodeWriter.cs index ae98d0118b5..52579e77dd7 100644 --- a/src/AutoRest.CSharp/Common/Generation/Writers/CodeWriter.cs +++ b/src/AutoRest.CSharp/Common/Generation/Writers/CodeWriter.cs @@ -220,17 +220,6 @@ public void UseNamespace(string @namespace) _usingNamespaces.Add(@namespace); } - public void WriteRawXmlDocumentation(FormattableString? content) - { - if (content is null) - return; - - var lines = content.ToString().Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); - var xmlLines = string.Join('\n', lines.Select(l => "/// " + l)); - AppendRaw(xmlLines); - Line(); - } - public CodeWriter AppendXmlDocumentation(FormattableString startTag, FormattableString endTag, FormattableString content) { const string xmlDoc = "/// "; diff --git a/src/AutoRest.CSharp/Common/Generation/Writers/CodeWriterExtensions.cs b/src/AutoRest.CSharp/Common/Generation/Writers/CodeWriterExtensions.cs index c29bd923bb5..410d6aae06b 100644 --- a/src/AutoRest.CSharp/Common/Generation/Writers/CodeWriterExtensions.cs +++ b/src/AutoRest.CSharp/Common/Generation/Writers/CodeWriterExtensions.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Diagnostics; using System.Linq; using AutoRest.CSharp.Common.Output.Builders; @@ -751,34 +750,5 @@ static void WritePropertyAccessorModifiers(CodeWriter writer, MethodSignatureMod .AppendRawIf("private ", modifiers.HasFlag(MethodSignatureModifiers.Private)); } } - - public static void WriteOverloadMethod(this CodeWriter writer, OverloadMethodSignature overloadMethod) - { - writer.WriteRawXmlDocumentation(overloadMethod.Description); - if (overloadMethod.IsHiddenFromUser) - { - writer.Line($"[{typeof(EditorBrowsableAttribute)}({typeof(EditorBrowsableState)}.{nameof(EditorBrowsableState.Never)})]"); - } - using (writer.WriteMethodDeclaration(overloadMethod.PreviousMethodSignature)) - { - writer.Line(); - var awaitOperation = overloadMethod.PreviousMethodSignature.Modifiers.HasFlag(MethodSignatureModifiers.Async) ? "await " : ""; - writer.Append($"return {awaitOperation}{overloadMethod.MethodSignature.Name}("); - var set = overloadMethod.MissingParameters.ToHashSet(Parameter.TypeAndNameEqualityComparer); - foreach (var parameter in overloadMethod.MethodSignature.Parameters) - { - if (set.Contains(parameter)) - { - writer.Append($"{parameter.DefaultValue?.Value ?? "default"}, "); - } - else - { - writer.Append($"{parameter.Name}, "); - } - } - writer.RemoveTrailingComma(); - writer.Line($");"); - } - } } } diff --git a/src/AutoRest.CSharp/Common/Generation/Writers/ModelFactoryWriter.cs b/src/AutoRest.CSharp/Common/Generation/Writers/ModelFactoryWriter.cs index 2a416d5f9d5..fd86a4974c2 100644 --- a/src/AutoRest.CSharp/Common/Generation/Writers/ModelFactoryWriter.cs +++ b/src/AutoRest.CSharp/Common/Generation/Writers/ModelFactoryWriter.cs @@ -1,13 +1,6 @@ // 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.Output.Models.Types; -using AutoRest.CSharp.Generation.Types; -using AutoRest.CSharp.Input; -using AutoRest.CSharp.Output.Models; using AutoRest.CSharp.Output.Models.Types; namespace AutoRest.CSharp.Generation.Writers @@ -34,17 +27,11 @@ public void Write() _writer.WriteXmlDocumentationSummary(This.Description); using (_writer.Scope($"{This.Declaration.Accessibility} static partial class {This.Type:D}")) { - foreach (var method in This.OutputMethods) + foreach (var method in This.Methods) { _writer.WriteMethodDocumentation(method.Signature); _writer.WriteMethod(method); } - - foreach (OverloadMethodSignature overloadMethod in This.SignatureType!.OverloadMethods) - { - _writer.WriteOverloadMethod(overloadMethod); - _writer.Line(); - } } } } diff --git a/src/AutoRest.CSharp/Common/Input/Source/SourceInputModel.cs b/src/AutoRest.CSharp/Common/Input/Source/SourceInputModel.cs index 3972c52287b..8e8c84e472f 100644 --- a/src/AutoRest.CSharp/Common/Input/Source/SourceInputModel.cs +++ b/src/AutoRest.CSharp/Common/Input/Source/SourceInputModel.cs @@ -13,22 +13,19 @@ namespace AutoRest.CSharp.Input.Source { public class SourceInputModel { + private readonly Compilation _compilation; private readonly CompilationInput? _existingCompilation; private readonly CodeGenAttributes _codeGenAttributes; private readonly Dictionary _nameMap = new Dictionary(StringComparer.OrdinalIgnoreCase); - public Compilation Customization { get; } - public Compilation? PreviousContract { get; } - - public SourceInputModel(Compilation customization, CompilationInput? existingCompilation = null, Compilation? previousContract = null) + public SourceInputModel(Compilation compilation, CompilationInput? existingCompilation = null) { - Customization = customization; - PreviousContract = previousContract; + _compilation = compilation; _existingCompilation = existingCompilation; - _codeGenAttributes = new CodeGenAttributes(customization); + _codeGenAttributes = new CodeGenAttributes(compilation); - IAssemblySymbol assembly = Customization.Assembly; + IAssemblySymbol assembly = _compilation.Assembly; foreach (IModuleSymbol module in assembly.Modules) { @@ -44,8 +41,8 @@ public SourceInputModel(Compilation customization, CompilationInput? existingCom public IReadOnlyList? GetServiceVersionOverrides() { - var osvAttributeType = Customization.GetTypeByMetadataName(typeof(CodeGenOverrideServiceVersionsAttribute).FullName!)!; - var osvAttribute = Customization.Assembly.GetAttributes() + var osvAttributeType = _compilation.GetTypeByMetadataName(typeof(CodeGenOverrideServiceVersionsAttribute).FullName!)!; + var osvAttribute = _compilation.Assembly.GetAttributes() .FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, osvAttributeType)); return osvAttribute?.ConstructorArguments[0].Values.Select(v => v.Value).OfType().ToList(); @@ -70,7 +67,7 @@ public SourceInputModel(Compilation customization, CompilationInput? existingCom if (!_nameMap.TryGetValue(name, out var type) && !_nameMap.TryGetValue(fullyQualifiedMetadataName, out type)) { - type = includeArmCore ? Customization.GetTypeByMetadataName(fullyQualifiedMetadataName) : Customization.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName); + type = includeArmCore ? _compilation.GetTypeByMetadataName(fullyQualifiedMetadataName) : _compilation.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName); } return type; diff --git a/src/AutoRest.CSharp/Common/Output/Models/MethodSignature.cs b/src/AutoRest.CSharp/Common/Output/Models/MethodSignature.cs index dd4aa1fe135..204c0cba40b 100644 --- a/src/AutoRest.CSharp/Common/Output/Models/MethodSignature.cs +++ b/src/AutoRest.CSharp/Common/Output/Models/MethodSignature.cs @@ -3,15 +3,13 @@ using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Text; using System.Threading.Tasks; using AutoRest.CSharp.Generation.Types; using AutoRest.CSharp.Generation.Writers; -using AutoRest.CSharp.Mgmt.Decorator; using AutoRest.CSharp.Output.Models.Shared; using Azure; -using Microsoft.CodeAnalysis; using static AutoRest.CSharp.Output.Models.MethodSignatureModifiers; namespace AutoRest.CSharp.Output.Models @@ -19,19 +17,8 @@ namespace AutoRest.CSharp.Output.Models internal record MethodSignature(string Name, FormattableString? Summary, FormattableString? Description, MethodSignatureModifiers Modifiers, CSharpType? ReturnType, FormattableString? ReturnDescription, IReadOnlyList Parameters, IReadOnlyList? Attributes = null, IReadOnlyList? GenericArguments = null, IReadOnlyDictionary? GenericParameterConstraints = null, CSharpType? ExplicitInterface = null, string? NonDocumentComment = null) : MethodSignatureBase(Name, Summary, Description, NonDocumentComment, Modifiers, Parameters, Attributes ?? Array.Empty()) { - public static IEqualityComparer ParameterAndReturnTypeEqualityComparer = new MethodSignatureParameterAndReturnTypeEqualityComparer(); - public MethodSignature WithAsync(bool isAsync) => isAsync ? MakeAsync() : MakeSync(); - public MethodSignature DisableOptionalParameters() - { - if (Parameters.All(p => p.DefaultValue is null)) - { - return this; - } - return this with { Parameters = Parameters.Select(p => p.ToRequired()).ToList() }; - } - private MethodSignature MakeAsync() { if (Modifiers.HasFlag(Async) || ReturnType != null && TypeFactory.IsAsyncPageable(ReturnType)) @@ -111,31 +98,5 @@ private MethodSignature MakeSync() } public FormattableString GetCRef() => $"{Name}({Parameters.GetTypesFormattable()})"; - - private class MethodSignatureParameterAndReturnTypeEqualityComparer : IEqualityComparer - { - public bool Equals(MethodSignature? x, MethodSignature? y) - { - if (ReferenceEquals(x, y)) - { - return true; - } - - if (x is null || y is null) - { - return false; - } - - var result = x.Name == x.Name - && x.ReturnType == y.ReturnType - && x.Parameters.SequenceEqual(y.Parameters, Parameter.TypeAndNameEqualityComparer); - return result; - } - - public int GetHashCode([DisallowNull] MethodSignature obj) - { - return HashCode.Combine(obj.Name, obj.ReturnType); - } - } } } diff --git a/src/AutoRest.CSharp/Common/Output/Models/OverloadMethodSignature.cs b/src/AutoRest.CSharp/Common/Output/Models/OverloadMethodSignature.cs deleted file mode 100644 index eaba2d3ac4c..00000000000 --- a/src/AutoRest.CSharp/Common/Output/Models/OverloadMethodSignature.cs +++ /dev/null @@ -1,27 +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.Output.Models.Shared; - -namespace AutoRest.CSharp.Output.Models -{ - internal class OverloadMethodSignature - { - public MethodSignature MethodSignature { get; } - public MethodSignature PreviousMethodSignature { get; } - public IReadOnlyList MissingParameters { get; } - public FormattableString? Description { get; } - public bool IsHiddenFromUser { get; } - - public OverloadMethodSignature(MethodSignature methodSignature, MethodSignature previousMethodSignature, IReadOnlyList missingParameters, FormattableString? description, bool isHiddenFromUser) - { - MethodSignature = methodSignature; - PreviousMethodSignature = previousMethodSignature; - MissingParameters = missingParameters; - Description = description; - IsHiddenFromUser = isHiddenFromUser; - } - } -} diff --git a/src/AutoRest.CSharp/Common/Output/Models/Shared/Parameter.cs b/src/AutoRest.CSharp/Common/Output/Models/Shared/Parameter.cs index 4b216d28a8a..671229060d5 100644 --- a/src/AutoRest.CSharp/Common/Output/Models/Shared/Parameter.cs +++ b/src/AutoRest.CSharp/Common/Output/Models/Shared/Parameter.cs @@ -9,19 +9,15 @@ using AutoRest.CSharp.Generation.Types; using AutoRest.CSharp.Generation.Writers; using AutoRest.CSharp.Input; -using AutoRest.CSharp.Mgmt.AutoRest; -using AutoRest.CSharp.Mgmt.Decorator; using AutoRest.CSharp.Output.Builders; using AutoRest.CSharp.Output.Models.Requests; using AutoRest.CSharp.Output.Models.Serialization; using AutoRest.CSharp.Utilities; -using Microsoft.CodeAnalysis; namespace AutoRest.CSharp.Output.Models.Shared { internal record Parameter(string Name, FormattableString? Description, CSharpType Type, Constant? DefaultValue, ValidationType Validation, FormattableString? Initializer, bool IsApiVersionParameter = false, bool IsEndpoint = false, bool IsResourceIdentifier = false, bool SkipUrlEncoding = false, RequestLocation RequestLocation = RequestLocation.None, SerializationFormat SerializationFormat = SerializationFormat.Default, bool IsPropertyBag = false) { - public static IEqualityComparer TypeAndNameEqualityComparer = new ParameterTypeAndNameEqualityComparer(); public CSharpAttribute[] Attributes { get; init; } = Array.Empty(); public bool IsOptionalInSignature => DefaultValue != null; @@ -37,20 +33,6 @@ public static Parameter FromModelProperty(in InputModelProperty property, string return new Parameter(name, $"{property.Description}", propertyType, null, validation, null); } - public static Parameter? FromParameterSymbol(IParameterSymbol parameterSymbol) - { - var parameterName = parameterSymbol.Name; - if (MgmtContext.TypeFactory.TryCreateType(parameterSymbol.Type, out var parameterType)) - { - return new Parameter(parameterName, null, parameterType, null, ValidationType.None, null); - } - else - { - // TODO: handle missing type from MgmtOutputLibrary - return null; - } - } - public static Parameter FromInputParameter(in InputParameter operationParameter, CSharpType type, TypeFactory typeFactory, bool shouldKeepClientDefaultValue = false) { var name = ConstructParameterVariableName(operationParameter, type); @@ -304,32 +286,6 @@ public bool Equals(Parameter? x, Parameter? y) public int GetHashCode([DisallowNull] Parameter obj) => obj.Type.GetHashCode(); } - - private class ParameterTypeAndNameEqualityComparer : IEqualityComparer - { - public bool Equals(Parameter? x, Parameter? y) - { - if (Object.ReferenceEquals(x, y)) - { - return true; - } - - if (x is null || y is null) - { - return false; - } - - // We can't use CsharpType.Equals here because they can have different implementations from different versions - var result = x.Type.EqualsByName(y.Type) && x.Name == y.Name; - return result; - } - - public int GetHashCode([DisallowNull] Parameter obj) - { - // remove type as part of the hash code generation as the type might have changes between versions - return HashCode.Combine(obj.Name); - } - } } internal enum ValidationType diff --git a/src/AutoRest.CSharp/Common/Output/Models/Types/ModelFactoryTypeProvider.cs b/src/AutoRest.CSharp/Common/Output/Models/Types/ModelFactoryTypeProvider.cs index 4fbd92b9fb6..6ab4cf8a6ec 100644 --- a/src/AutoRest.CSharp/Common/Output/Models/Types/ModelFactoryTypeProvider.cs +++ b/src/AutoRest.CSharp/Common/Output/Models/Types/ModelFactoryTypeProvider.cs @@ -21,8 +21,6 @@ using Azure.Core.Expressions.DataFactory; using Azure.ResourceManager.Models; using static AutoRest.CSharp.Common.Output.Models.Snippets; -using Microsoft.CodeAnalysis; -using System.Runtime.CompilerServices; namespace AutoRest.CSharp.Output.Models.Types { @@ -31,19 +29,8 @@ internal sealed class ModelFactoryTypeProvider : TypeProvider protected override string DefaultName { get; } protected override string DefaultAccessibility { get; } - // TODO: remove this intermediate state once we generate it before output types - private IReadOnlyList? _methods; - - // This method should only be called from OutputMethods as intermediate state. - private IReadOnlyList ShouldNotBeUsedForOutput([CallerMemberName] string caller = "") - { - Debug.Assert(caller == nameof(OutputMethods) || caller == nameof(SignatureType), $"This method should not be used for output. Caller: {caller}"); - return _methods ??= Models!.Select(CreateMethod).ToList(); - } - - private IReadOnlyList? _outputMethods; - public IReadOnlyList OutputMethods - => _outputMethods ??= ShouldNotBeUsedForOutput().Where(x => !SignatureType.MethodsToSkip.Contains(x.Signature)).ToList(); + private IEnumerable? _methods; + public IEnumerable Methods => _methods ??= Models.Select(CreateMethod); public IEnumerable Models { get; } @@ -51,10 +38,10 @@ public IReadOnlyList OutputMethods internal string FullName => $"{Type.Namespace}.{Type.Name}"; - private ModelFactoryTypeProvider(IEnumerable objectTypes, string defaultClientName, string defaultNamespace, SourceInputModel? sourceInputModel) - : base(defaultNamespace, sourceInputModel) + private ModelFactoryTypeProvider(IEnumerable objectTypes, string defaultClientName, string defaultNamespace, SourceInputModel? sourceInputModel) : base(defaultNamespace, sourceInputModel) { Models = objectTypes; + DefaultName = $"{defaultClientName}ModelFactory".ToCleanName(); DefaultAccessibility = "public"; ExistingModelFactoryMethods = typeof(ResourceManagerModelFactory).GetMethods(BindingFlags.Static | BindingFlags.Public).ToHashSet(); @@ -83,7 +70,7 @@ private ModelFactoryTypeProvider(IEnumerable objectTypes return new ModelFactoryTypeProvider(objectTypes, defaultRPName, defaultNamespace, sourceInputModel); } - private static string GetRPName(string defaultNamespace) + public static string GetRPName(string defaultNamespace) { // for mgmt plane packages, we always have the prefix `Arm` on the name of model factories, except for Azure.ResourceManager var prefix = Configuration.AzureArm && !Configuration.MgmtConfiguration.IsArmCore ? "Arm" : string.Empty; @@ -101,9 +88,6 @@ private static string GetDefaultNamespace() public HashSet ExistingModelFactoryMethods { get; } - private SignatureType? _signatureType; - public override SignatureType SignatureType => _signatureType ??= new SignatureType(ShouldNotBeUsedForOutput().Select(x => (MethodSignature)x.Signature).ToList(), _sourceInputModel, DefaultNamespace, DefaultName); - private ValueExpression BuildPropertyAssignmentExpression(Parameter parameter, ObjectTypeProperty property) { ValueExpression p = parameter; @@ -136,7 +120,7 @@ private ValueExpression BuildPropertyAssignmentExpression(Parameter parameter, O case { IsFrameworkType: false, Implementation: SerializableObjectType serializableObjectType }: // get the type of the first parameter of its ctor var to = serializableObjectType.SerializationConstructor.Signature.Parameters.First().Type; - result = Snippets.New.Instance(parentPropertyType, result.GetConversion(from, to)); + result = New.Instance(parentPropertyType, result.GetConversion(from, to)); break; case { IsFrameworkType: false, Implementation: SystemObjectType systemObjectType }: // for the case of SystemObjectType, the serialization constructor is internal and the definition of this class might be outside of this assembly, we need to use its corresponding model factory to construct it @@ -260,7 +244,7 @@ private Method CreateMethod(SerializableObjectType model) { // write the initializers and validations new ParameterValidationBlock(methodParameters, true), - Return(Snippets.New.Instance(ctorToCall.Signature, methodArguments)) + Return(New.Instance(ctorToCall.Signature, methodArguments)) }; return new(signature, methodBody); diff --git a/src/AutoRest.CSharp/Common/Output/Models/Types/ModelTypeProvider.cs b/src/AutoRest.CSharp/Common/Output/Models/Types/ModelTypeProvider.cs index a1f2967e45e..af62e531110 100644 --- a/src/AutoRest.CSharp/Common/Output/Models/Types/ModelTypeProvider.cs +++ b/src/AutoRest.CSharp/Common/Output/Models/Types/ModelTypeProvider.cs @@ -27,6 +27,7 @@ internal sealed class ModelTypeProvider : SerializableObjectType private ConstructorSignature? _serializationConstructor; private InputModelType _inputModel; private TypeFactory _typeFactory; + private SourceInputModel? _sourceInputModel; private InputModelType[]? _derivedTypes; private SerializableObjectType? _defaultDerivedType; @@ -49,6 +50,7 @@ public ModelTypeProvider(InputModelType inputModel, string defaultNamespace, Sou { _typeFactory = typeFactory!; _inputModel = inputModel; + _sourceInputModel = sourceInputModel; DefaultName = inputModel.Name.ToCleanName(); DefaultAccessibility = inputModel.Accessibility ?? "public"; IsAccessibilityOverridden = inputModel.Accessibility != null; diff --git a/src/AutoRest.CSharp/Common/Output/Models/Types/SignatureType.cs b/src/AutoRest.CSharp/Common/Output/Models/Types/SignatureType.cs deleted file mode 100644 index e14b43186be..00000000000 --- a/src/AutoRest.CSharp/Common/Output/Models/Types/SignatureType.cs +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Collections.Generic; -using Microsoft.CodeAnalysis; -using AutoRest.CSharp.Input.Source; -using AutoRest.CSharp.Mgmt.AutoRest; -using AutoRest.CSharp.Output.Models.Shared; -using System; -using System.Linq; -using AutoRest.CSharp.Mgmt.Decorator; -using System.Diagnostics.CodeAnalysis; - -namespace AutoRest.CSharp.Output.Models.Types -{ - /// - /// This type holds three portions of codes: - /// - current - /// - custom - /// - baseline contract - /// current union custom compare with baseline contract outputs the changeset, we can apply different rules with it. - /// - internal class SignatureType - { - private readonly string _defaultNamespace; - private readonly string _defaultName; - private readonly SignatureType? _customization; - private readonly SignatureType? _baselineContract; - private readonly MethodChangeset? _methodChangeset; - - // Missing means the method with the same name is missing from the current contract - // Updated means the method with the same name is updated in the current contract, and the list contains the previous method and current methods including overload ones - private record MethodChangeset(IReadOnlyList Missing, IReadOnlyList<(List Current, MethodSignature Previous)> Updated) { } - - public SignatureType(IReadOnlyList methods, SourceInputModel? sourceInputModel, string defaultNamespace, string defaultName) - { - Methods = methods; - _defaultNamespace = defaultNamespace; - _defaultName = defaultName; - if (sourceInputModel is not null) - { - _customization = new SignatureType(PopulateMethodsFromCompilation(sourceInputModel?.Customization), null, defaultNamespace, defaultName); - _baselineContract = new SignatureType(PopulateMethodsFromCompilation(sourceInputModel?.PreviousContract), null, defaultNamespace, defaultName); - _methodChangeset ??= CompareMethods(Methods.Union(_customization?.Methods ?? Array.Empty(), MethodSignature.ParameterAndReturnTypeEqualityComparer), _baselineContract?.Methods); - } - } - - private IReadOnlyList? _overloadMethods; - public IReadOnlyList OverloadMethods => _overloadMethods ??= EnsureOverloadMethods(); - - private IReadOnlyList EnsureOverloadMethods() - { - var overloadMethods = new List(); - var updated = _methodChangeset?.Updated; - if (updated is null) - { - return Array.Empty(); - } - - foreach (var (current, previous) in updated) - { - if (TryGetPreviousMethodWithLessOptionalParameters(current, previous, out var currentMethodToCall, out var missingParameters)) - { - overloadMethods.Add(new OverloadMethodSignature(currentMethodToCall, previous.DisableOptionalParameters(), missingParameters, previous.Description, true)); - } - } - return overloadMethods; - } - - private IReadOnlySet? _methodsToSkip; - public IReadOnlySet MethodsToSkip => _methodsToSkip ??= EnsureMethodsToSkip(); - private IReadOnlySet EnsureMethodsToSkip() - { - if (_customization is null) - { - return new HashSet(); - } - return Methods.Intersect(_customization.Methods, MethodSignature.ParameterAndReturnTypeEqualityComparer).ToHashSet(MethodSignature.ParameterAndReturnTypeEqualityComparer); - } - - private bool TryGetPreviousMethodWithLessOptionalParameters(IList currentMethods, MethodSignature previousMethod, [NotNullWhen(true)] out MethodSignature? currentMethodToCall, [NotNullWhen(true)] out IReadOnlyList? missingParameters) - { - foreach (var item in currentMethods) - { - if (item.Parameters.Count <= previousMethod.Parameters.Count) - { - continue; - } - - if (!CurrentContainAllPreviousParameters(previousMethod, item)) - { - continue; - } - - // We can't use CsharpType.Equals here because they could have different implementations from different versions - if (previousMethod.ReturnType is null && item.ReturnType is not null) - { - continue; - } - if (previousMethod.ReturnType is not null && !previousMethod.ReturnType.EqualsByName(item.ReturnType)) - { - continue; - } - - var parameters = item.Parameters.Except(previousMethod.Parameters, Parameter.TypeAndNameEqualityComparer); - if (parameters.All(x => x.IsOptionalInSignature)) - { - missingParameters = parameters.ToList(); - currentMethodToCall = item; - return true; - } - } - missingParameters = null; - currentMethodToCall = null; - return false; - } - - private bool CurrentContainAllPreviousParameters(MethodSignature previousMethod, MethodSignature currentMethod) - { - var set = currentMethod.Parameters.ToHashSet(Parameter.TypeAndNameEqualityComparer); - foreach (var parameter in previousMethod.Parameters) - { - if (!set.Contains(parameter)) - { - return false; - } - } - return true; - } - - private static MethodChangeset? CompareMethods(IEnumerable currentMethods, IEnumerable? previousMethods) - { - if (previousMethods is null) - { - return null; - } - var missing = new List(); - var updated = new List<(List Current, MethodSignature Previous)>(); - var set = currentMethods.ToHashSet(MethodSignature.ParameterAndReturnTypeEqualityComparer); - var dict = new Dictionary>(); - foreach (var item in currentMethods) - { - if (!dict.TryGetValue(item.Name, out var list)) - { - dict.Add(item.Name, new List { item }); - } - else - { - list.Add(item); - } - } - foreach (var item in previousMethods) - { - if (!set.Contains(item)) - { - if (dict.TryGetValue(item.Name, out var currentOverloadMethods)) - { - updated.Add((currentOverloadMethods, item)); - } - else - { - missing.Add(item); - } - } - } - return new(missing, updated); - } - - public IReadOnlyList Methods { get; } - - private IReadOnlyList PopulateMethodsFromCompilation(Compilation? compilation) - { - if (compilation is null) - { - return new List(); - } - var type = compilation.GetTypeByMetadataName($"{_defaultNamespace}.{_defaultName}"); - if (type is null) - { - return new List(); - } - return PopulateMethods(type); - } - - private IReadOnlyList PopulateMethods(INamedTypeSymbol? typeSymbol) - { - var result = new List(); - if (typeSymbol is null) - { - // TODO: handle missing type - return result; - } - var methods = typeSymbol!.GetMembers().OfType(); - foreach (var method in methods) - { - var description = method.GetDocumentationCommentXml(); - if (!MgmtContext.TypeFactory.TryCreateType(method.ReturnType, out var returnType)) - { - // TODO: handle missing method return type from MgmtOutputLibrary - continue; - } - - // TODO: handle missing parameter type from MgmtOutputLibrary - var parameters = new List(); - foreach (var parameter in method.Parameters) - { - var methodParameter = Parameter.FromParameterSymbol(parameter); - if (methodParameter is not null) - { - parameters.Add(methodParameter); - } - } - result.Add(new MethodSignature(method.Name, null, $"{description}", MapModifiers(method), returnType, null, parameters)); - } - return result; - } - - private static MethodSignatureModifiers MapModifiers(IMethodSymbol methodSymbol) - { - var modifiers = MethodSignatureModifiers.None; - var accessibility = methodSymbol.DeclaredAccessibility; - switch (accessibility) - { - case Accessibility.Public: - modifiers |= MethodSignatureModifiers.Public; - break; - case Accessibility.Internal: - modifiers |= MethodSignatureModifiers.Internal; - break; - case Accessibility.Private: - modifiers |= MethodSignatureModifiers.Private; - break; - case Accessibility.Protected: - modifiers |= MethodSignatureModifiers.Protected; - break; - case Accessibility.ProtectedAndInternal: - modifiers |= MethodSignatureModifiers.Protected | MethodSignatureModifiers.Internal; - break; - } - if (methodSymbol.IsStatic) - { - modifiers |= MethodSignatureModifiers.Static; - } - if (methodSymbol.IsAsync) - { - modifiers |= MethodSignatureModifiers.Async; - } - if (methodSymbol.IsVirtual) - { - modifiers |= MethodSignatureModifiers.Virtual; - } - if (methodSymbol.IsOverride) - { - modifiers |= MethodSignatureModifiers.Override; - } - return modifiers; - } - } -} diff --git a/src/AutoRest.CSharp/Common/Output/Models/Types/SystemObjectType.cs b/src/AutoRest.CSharp/Common/Output/Models/Types/SystemObjectType.cs index bee883f09d2..e5556aa55f7 100644 --- a/src/AutoRest.CSharp/Common/Output/Models/Types/SystemObjectType.cs +++ b/src/AutoRest.CSharp/Common/Output/Models/Types/SystemObjectType.cs @@ -5,6 +5,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Linq; using System.Reflection; using System.Text; @@ -37,11 +38,13 @@ public static SystemObjectType Create(Type type, string defaultNamespace, Source } private readonly Type _type; + private readonly SourceInputModel? _sourceInputModel; private readonly IReadOnlyDictionary _backingProperties; private SystemObjectType(Type type, string defaultNamespace, SourceInputModel? sourceInputModel, IEnumerable? backingProperties) : base(defaultNamespace, sourceInputModel) { _type = type; + _sourceInputModel = sourceInputModel; DefaultName = GetNameWithoutGeneric(type); _backingProperties = backingProperties?.ToDictionary(p => p.Declaration.Name) ?? new Dictionary(); } diff --git a/src/AutoRest.CSharp/Common/Output/Models/Types/TypeProvider.cs b/src/AutoRest.CSharp/Common/Output/Models/Types/TypeProvider.cs index cd3e2ab9744..257ea9a3915 100644 --- a/src/AutoRest.CSharp/Common/Output/Models/Types/TypeProvider.cs +++ b/src/AutoRest.CSharp/Common/Output/Models/Types/TypeProvider.cs @@ -19,16 +19,14 @@ internal abstract class TypeProvider protected string? _deprecated; private TypeDeclarationOptions? _type; - protected readonly SourceInputModel? _sourceInputModel; protected TypeProvider(string defaultNamespace, SourceInputModel? sourceInputModel) { - _sourceInputModel = sourceInputModel; DefaultNamespace = defaultNamespace; _existingType = new Lazy(() => sourceInputModel?.FindForType(DefaultNamespace, DefaultName)); } - protected TypeProvider(BuildContext context) : this(context.DefaultNamespace, context.SourceInputModel) { } + protected TypeProvider(BuildContext context) : this(context.DefaultNamespace, context.SourceInputModel) {} public CSharpType Type => new(this, TypeKind is TypeKind.Struct or TypeKind.Enum, this is EnumType); public TypeDeclarationOptions Declaration => _type ??= BuildType(); @@ -41,7 +39,6 @@ protected TypeProvider(BuildContext context) : this(context.DefaultNamespace, co protected virtual TypeKind TypeKind { get; } = TypeKind.Class; protected virtual bool IsAbstract { get; } = false; protected INamedTypeSymbol? ExistingType => _existingType.Value; - public virtual SignatureType? SignatureType => null; internal virtual Type? SerializeAs => null; diff --git a/src/AutoRest.CSharp/LowLevel/Output/LowLevelClient.cs b/src/AutoRest.CSharp/LowLevel/Output/LowLevelClient.cs index 48723870d2c..1c6f9921570 100644 --- a/src/AutoRest.CSharp/LowLevel/Output/LowLevelClient.cs +++ b/src/AutoRest.CSharp/LowLevel/Output/LowLevelClient.cs @@ -29,6 +29,7 @@ internal class LowLevelClient : TypeProvider private readonly IReadOnlyDictionary _clientParameterExamples; private readonly InputAuth _authorization; private readonly IEnumerable _operations; + private readonly SourceInputModel? _sourceInputModel; protected override string DefaultName { get; } protected override string DefaultAccessibility => "public"; @@ -77,6 +78,7 @@ public LowLevelClient(string name, string ns, string description, string library _clientParameterExamples = examples; _authorization = authorization; _operations = operations; + _sourceInputModel = sourceInputModel; SubClients = Array.Empty(); } diff --git a/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtContext.cs b/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtContext.cs index a242dcc1403..02ec5d44fc8 100644 --- a/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtContext.cs +++ b/src/AutoRest.CSharp/Mgmt/AutoRest/MgmtContext.cs @@ -4,7 +4,6 @@ using System; using System.Linq; using AutoRest.CSharp.Common.Output.Builders; -using AutoRest.CSharp.Generation.Types; using AutoRest.CSharp.Input; using AutoRest.CSharp.Output.Models.Types; @@ -17,8 +16,6 @@ internal static class MgmtContext public static MgmtOutputLibrary Library => Context.Library; - public static TypeFactory TypeFactory => Context.TypeFactory; - public static CodeModel CodeModel => Context.CodeModel; public static string DefaultNamespace => Context.DefaultNamespace; diff --git a/src/AutoRest.CSharp/Mgmt/Decorator/TypeExtensions.cs b/src/AutoRest.CSharp/Mgmt/Decorator/TypeExtensions.cs index 69c84e380e6..4051a763425 100644 --- a/src/AutoRest.CSharp/Mgmt/Decorator/TypeExtensions.cs +++ b/src/AutoRest.CSharp/Mgmt/Decorator/TypeExtensions.cs @@ -13,6 +13,31 @@ namespace AutoRest.CSharp.Mgmt.Decorator { internal static class TypeExtensions { + + /// + /// Check whether two CSharpType instances equal or not + /// This is not the same as left.Equals(right) because this function only checks the names + /// + /// + /// + /// + public static bool EqualsByName(this CSharpType left, CSharpType right) + { + if (left.Name != right.Name) + return false; + + if (left.Arguments.Length != right.Arguments.Length) + return false; + + for (int i = 0; i < left.Arguments.Length; i++) + { + if (left.Arguments[i].Name != right.Arguments[i].Name) + return false; + } + + return true; + } + public static CSharpType WrapPageable(this CSharpType type, bool isAsync) { return isAsync ? new CSharpType(typeof(AsyncPageable<>), type) : new CSharpType(typeof(Pageable<>), type); diff --git a/src/AutoRest.CSharp/Mgmt/Models/MgmtClientOperation.cs b/src/AutoRest.CSharp/Mgmt/Models/MgmtClientOperation.cs index ddec662c89f..c8de117a8ec 100644 --- a/src/AutoRest.CSharp/Mgmt/Models/MgmtClientOperation.cs +++ b/src/AutoRest.CSharp/Mgmt/Models/MgmtClientOperation.cs @@ -5,8 +5,10 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using System.Text; using AutoRest.CSharp.Generation.Types; using AutoRest.CSharp.Generation.Writers; +using AutoRest.CSharp.Mgmt.AutoRest; using AutoRest.CSharp.Mgmt.Decorator; using AutoRest.CSharp.Mgmt.Output; using AutoRest.CSharp.Output.Models; diff --git a/src/AutoRest.CSharp/Mgmt/Models/MgmtRestOperation.cs b/src/AutoRest.CSharp/Mgmt/Models/MgmtRestOperation.cs index da08af5121a..96fd45ebc36 100644 --- a/src/AutoRest.CSharp/Mgmt/Models/MgmtRestOperation.cs +++ b/src/AutoRest.CSharp/Mgmt/Models/MgmtRestOperation.cs @@ -211,7 +211,7 @@ public MgmtRestOperation(MgmtRestOperation other, string nameOverride, CSharpTyp try { - return finalSchema.Type == AllSchemaTypes.Object ? MgmtContext.Library.FindTypeForSchema(finalSchema) : MgmtContext.TypeFactory.CreateType(finalSchema, false); + return finalSchema.Type == AllSchemaTypes.Object ? MgmtContext.Library.FindTypeForSchema(finalSchema) : new TypeFactory(MgmtContext.Library).CreateType(finalSchema, false); } catch (Exception ex) { diff --git a/test/AutoRest.TestServer.Tests/Mgmt/TestProjects/MgmtCustomizationTests.cs b/test/AutoRest.TestServer.Tests/Mgmt/TestProjects/MgmtCustomizationTests.cs deleted file mode 100644 index f22bfa5bdfa..00000000000 --- a/test/AutoRest.TestServer.Tests/Mgmt/TestProjects/MgmtCustomizationTests.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Linq; -using NUnit.Framework; - -namespace AutoRest.TestServer.Tests.Mgmt.TestProjects -{ - internal class MgmtCustomizationTests : TestProjectTests - { - public MgmtCustomizationTests() : base("MgmtCustomizations") { } - - [TestCase("Cat", new string[] { "sleep", "jump" })] - [TestCase("Dog", new string[] { "sleep", "jump" })] - public void ValidateOverloadMethodsForModelFactory(string methodName, string[] parameterNames) - { - var classToCheck = FindModelFactory(); - ValidateOverloadMethods(classToCheck.Name, methodName, parameterNames, classToCheck); - } - - private static void ValidateOverloadMethods(string className, string methodName, string[] parameterNames, System.Type classToCheck) - { - var methods = classToCheck.GetMethods().Where(method => method.Name == methodName); - Assert.AreEqual(2, methods.Count(), $"Overloading methods not found for {className}.{methodName}"); - var overloadMethodParameterNames = methods.OrderBy(method => method.GetParameters().Length).Last().GetParameters().Select(x => x.Name.ToLowerInvariant()).ToList(); - - foreach (var name in parameterNames) - { - Assert.Contains(name, overloadMethodParameterNames, $"{name} is missing in overload method {className}.{methodName}"); - } - } - } -} diff --git a/test/AutoRest.TestServer.Tests/Mgmt/TestProjects/TestProjectTests.cs b/test/AutoRest.TestServer.Tests/Mgmt/TestProjects/TestProjectTests.cs index 242a52fd1be..d07e4158dd7 100644 --- a/test/AutoRest.TestServer.Tests/Mgmt/TestProjects/TestProjectTests.cs +++ b/test/AutoRest.TestServer.Tests/Mgmt/TestProjects/TestProjectTests.cs @@ -593,8 +593,6 @@ public IEnumerable FindAllCollections() } } - protected Type FindModelFactory() => MyTypes().Single(IsModelFactory); - private IEnumerable FindAllRestOperations() { Type[] allTypes = Assembly.GetExecutingAssembly().GetTypes(); diff --git a/test/AutoRest.TestServer.Tests/Mgmt/Unit/MgmtRestOperationTests.cs b/test/AutoRest.TestServer.Tests/Mgmt/Unit/MgmtRestOperationTests.cs index 64d8ab81893..575e030f5d9 100644 --- a/test/AutoRest.TestServer.Tests/Mgmt/Unit/MgmtRestOperationTests.cs +++ b/test/AutoRest.TestServer.Tests/Mgmt/Unit/MgmtRestOperationTests.cs @@ -2,6 +2,7 @@ // 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.Input; using AutoRest.CSharp.Mgmt.Models; diff --git a/test/AutoRest.TestServerLowLevel.Tests/LowLevel/Generation/ModelGenerationTestBase.cs b/test/AutoRest.TestServerLowLevel.Tests/LowLevel/Generation/ModelGenerationTestBase.cs index 2b8f993cf12..7320f621e0f 100644 --- a/test/AutoRest.TestServerLowLevel.Tests/LowLevel/Generation/ModelGenerationTestBase.cs +++ b/test/AutoRest.TestServerLowLevel.Tests/LowLevel/Generation/ModelGenerationTestBase.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.RegularExpressions; using AutoRest.CSharp.Common.Input; using AutoRest.CSharp.Generation.Types; using AutoRest.CSharp.Output.Models.Types; diff --git a/test/BaselineContract/MgmtCustomizations/MgmtCustomizations.dll b/test/BaselineContract/MgmtCustomizations/MgmtCustomizations.dll deleted file mode 100644 index 6a4ca43508f..00000000000 Binary files a/test/BaselineContract/MgmtCustomizations/MgmtCustomizations.dll and /dev/null differ diff --git a/test/BaselineContract/MgmtCustomizations/MgmtCustomizations.xml b/test/BaselineContract/MgmtCustomizations/MgmtCustomizations.xml deleted file mode 100644 index 83b50a962d5..00000000000 --- a/test/BaselineContract/MgmtCustomizations/MgmtCustomizations.xml +++ /dev/null @@ -1,2155 +0,0 @@ - - - - MgmtCustomizations - - - - A cat. - - - A cat can meow. We changed the readonly flag of this property using customization code - - - Initializes a new instance of Cat. - - - Initializes a new instance of Cat. - The kind of the pet. - The name of the pet. - - The size of the pet. This property here is mocking the following scenario: - Despite in the swagger it has a type of string, in the real payload of this request, the service is actually sending using a number, therefore the type in this swagger here is wrong and we have to fix it using customization code. - - Pet date of birth. - A cat can meow. - - - A dog. - - - A dog can bark. - - - Initializes a new instance of Dog. - - - Initializes a new instance of Dog. - The kind of the pet. - The name of the pet. - - The size of the pet. This property here is mocking the following scenario: - Despite in the swagger it has a type of string, in the real payload of this request, the service is actually sending using a number, therefore the type in this swagger here is wrong and we have to fix it using customization code. - - Pet date of birth. - A dog can bark. - - - - A pet - Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - The available derived classes include and . - - - - The size of the pet. Despite we write type string here, in the real payload of this request, it is actually sending using a number, therefore the type in this swagger here is wrong and we need to fix it using customization code. - - - Pet date of birth. - - - Initializes a new instance of Pet. - - - Initializes a new instance of Pet. - The kind of the pet. - The name of the pet. - - The size of the pet. This property here is mocking the following scenario: - Despite in the swagger it has a type of string, in the real payload of this request, the service is actually sending using a number, therefore the type in this swagger here is wrong and we have to fix it using customization code. - - Pet date of birth. - - - The kind of the pet. - - - The name of the pet. - - - The properties. - - - verifies this could work - - - Initializes a new instance of PetStoreProperties. - - - Initializes a new instance of PetStoreProperties. - The order. - - A pet - Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - The available derived classes include and . - - - - - A pet - Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - The available derived classes include and . - - - - Model factory for models. - - - Initializes a new instance of PetStoreData. - The id. - The name. - The resourceType. - The systemData. - The properties. - A new instance for mocking. - - - Initializes a new instance of Pet. - The name of the pet. - - The size of the pet. This property here is mocking the following scenario: - Despite in the swagger it has a type of string, in the real payload of this request, the service is actually sending using a number, therefore the type in this swagger here is wrong and we have to fix it using customization code. - - Pet date of birth. - A new instance for mocking. - - - Initializes a new instance of Cat. - The name of the pet. - - The size of the pet. This property here is mocking the following scenario: - Despite in the swagger it has a type of string, in the real payload of this request, the service is actually sending using a number, therefore the type in this swagger here is wrong and we have to fix it using customization code. - - Pet date of birth. - A cat can meow. - A new instance for mocking. - - - Initializes a new instance of Dog. - The name of the pet. - - The size of the pet. This property here is mocking the following scenario: - Despite in the swagger it has a type of string, in the real payload of this request, the service is actually sending using a number, therefore the type in this swagger here is wrong and we have to fix it using customization code. - - Pet date of birth. - A dog can bark. - A new instance for mocking. - - - The kind of the pet. - - - Cat. - - - Dog. - - - The list result of the rules. - - - Initializes a new instance of PetStoreListResult. - - - Initializes a new instance of PetStoreListResult. - The values. - - - The values. - - - The UnknownPet. - - - Initializes a new instance of UnknownPet. - The kind of the pet. - The name of the pet. - - The size of the pet. This property here is mocking the following scenario: - Despite in the swagger it has a type of string, in the real payload of this request, the service is actually sending using a number, therefore the type in this swagger here is wrong and we have to fix it using customization code. - - Pet date of birth. - - - A class to add extension methods to MgmtCustomizations. - - - - Gets an object representing a along with the instance operations that can be performed on it but with no data. - You can use to create a from its components. - - The instance the method will execute against. - The resource ID of the resource to get. - Returns a object. - - - Gets a collection of PetStoreResources in the ResourceGroupResource. - The instance the method will execute against. - An object representing collection of PetStoreResources and their operations over a PetStoreResource. - - - - Gets an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Get - - - - The instance the method will execute against. - Name of the endpoint under the profile which is unique globally. - The cancellation token to use. - is an empty string, and was expected to be non-empty. - is null. - - - - Gets an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Get - - - - The instance the method will execute against. - Name of the endpoint under the profile which is unique globally. - The cancellation token to use. - is an empty string, and was expected to be non-empty. - is null. - - - A class to add extension methods to ResourceGroupResource. - - - Initializes a new instance of the class for mocking. - - - Initializes a new instance of the class. - The client parameters to use in these operations. - The identifier of the resource that is the target of operations. - - - Gets a collection of PetStoreResources in the ResourceGroupResource. - An object representing collection of PetStoreResources and their operations over a PetStoreResource. - - - Initializes a new instance of MgmtCustomizationsArmOperation for mocking. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Initializes a new instance of MgmtCustomizationsArmOperation for mocking. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A class representing the PetStore data model. - A pet store - - - - Initializes a new instance of PetStoreData. - - - Initializes a new instance of PetStoreData. - The id. - The name. - The resourceType. - The systemData. - The properties. - - - The properties. - - - - A class representing a collection of and their operations. - Each in the collection will belong to the same instance of . - To get a instance call the GetPetStores method from an instance of . - - - - Initializes a new instance of the class for mocking. - - - Initializes a new instance of the class. - The client parameters to use in these operations. - The identifier of the parent resource that is the target of operations. - - - - Creates a new CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Create - - - - if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - Name of the endpoint under the profile which is unique globally. - Endpoint properties. - The cancellation token to use. - is an empty string, and was expected to be non-empty. - or is null. - - - - Creates a new CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Create - - - - if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - Name of the endpoint under the profile which is unique globally. - Endpoint properties. - The cancellation token to use. - is an empty string, and was expected to be non-empty. - or is null. - - - - Gets an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Get - - - - Name of the endpoint under the profile which is unique globally. - The cancellation token to use. - is an empty string, and was expected to be non-empty. - is null. - - - - Gets an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Get - - - - Name of the endpoint under the profile which is unique globally. - The cancellation token to use. - is an empty string, and was expected to be non-empty. - is null. - - - - Gets an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore - - - Operation Id - PetStores_List - - - - The cancellation token to use. - An async collection of that may take multiple service requests to iterate over. - - - - Gets an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore - - - Operation Id - PetStores_List - - - - The cancellation token to use. - A collection of that may take multiple service requests to iterate over. - - - - Checks to see if the resource exists in azure. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Get - - - - Name of the endpoint under the profile which is unique globally. - The cancellation token to use. - is an empty string, and was expected to be non-empty. - is null. - - - - Checks to see if the resource exists in azure. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Get - - - - Name of the endpoint under the profile which is unique globally. - The cancellation token to use. - is an empty string, and was expected to be non-empty. - is null. - - - - Tries to get details for this resource from the service. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Get - - - - Name of the endpoint under the profile which is unique globally. - The cancellation token to use. - is an empty string, and was expected to be non-empty. - is null. - - - - Tries to get details for this resource from the service. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Get - - - - Name of the endpoint under the profile which is unique globally. - The cancellation token to use. - is an empty string, and was expected to be non-empty. - is null. - - - - A Class representing a PetStore along with the instance operations that can be performed on it. - If you have a you can construct a - from an instance of using the GetPetStoreResource method. - Otherwise you can get one from its parent resource using the GetPetStore method. - - - - Generate the resource identifier of a instance. - - - Initializes a new instance of the class for mocking. - - - Initializes a new instance of the class. - The client parameters to use in these operations. - The resource that is the target of operations. - - - Initializes a new instance of the class. - The client parameters to use in these operations. - The identifier of the resource that is the target of operations. - - - Gets the resource type for the operations. - - - Gets whether or not the current instance has data. - - - Gets the data representing this Feature. - Throws if there is no data loaded in the current instance. - - - - Gets an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Get - - - - The cancellation token to use. - - - - Gets an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Get - - - - The cancellation token to use. - - - - Deletes an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Delete - - - - if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - The cancellation token to use. - - - - Deletes an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Delete - - - - if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - The cancellation token to use. - - - - Creates a new CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Create - - - - if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - Endpoint properties. - The cancellation token to use. - is null. - - - - Creates a new CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - - - Request Path - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Pets/petStore/{name} - - - Operation Id - PetStores_Create - - - - if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. - Endpoint properties. - The cancellation token to use. - is null. - - - Initializes a new instance of PetStoresRestOperations. - The HTTP pipeline for sending and receiving REST requests and responses. - The application id to use for user agent. - server parameter. - Api Version. - or is null. - - - Gets an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - Name of the Resource group within the Azure subscription. - The cancellation token to use. - or is null. - or is an empty string, and was expected to be non-empty. - - - Gets an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - Name of the Resource group within the Azure subscription. - The cancellation token to use. - or is null. - or is an empty string, and was expected to be non-empty. - - - Gets an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - Name of the Resource group within the Azure subscription. - Name of the endpoint under the profile which is unique globally. - The cancellation token to use. - , or is null. - , or is an empty string, and was expected to be non-empty. - - - Gets an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - Name of the Resource group within the Azure subscription. - Name of the endpoint under the profile which is unique globally. - The cancellation token to use. - , or is null. - , or is an empty string, and was expected to be non-empty. - - - Creates a new CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - Name of the Resource group within the Azure subscription. - Name of the endpoint under the profile which is unique globally. - Endpoint properties. - The cancellation token to use. - , , or is null. - , or is an empty string, and was expected to be non-empty. - - - Creates a new CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - Name of the Resource group within the Azure subscription. - Name of the endpoint under the profile which is unique globally. - Endpoint properties. - The cancellation token to use. - , , or is null. - , or is an empty string, and was expected to be non-empty. - - - Deletes an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - Name of the Resource group within the Azure subscription. - Name of the endpoint under the profile which is unique globally. - The cancellation token to use. - , or is null. - , or is an empty string, and was expected to be non-empty. - - - Deletes an existing CDN endpoint with the specified endpoint name under the specified subscription, resource group and profile. - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - Name of the Resource group within the Azure subscription. - Name of the endpoint under the profile which is unique globally. - The cancellation token to use. - , or is null. - , or is an empty string, and was expected to be non-empty. - - - - Provides a container for content encoded using multipart/form-data MIME type. - - - - - Initializes a new instance of the class. - - The multipart sub type. - The boundary string for the multipart form data content. - - - - Add content type header to the request. - - The request. - - - - Add HTTP content to a collection of RequestContent objects that - get serialized to multipart/form-data MIME type. - - The Request content to add to the collection. - - - - Add HTTP content to a collection of RequestContent objects that - get serialized to multipart/form-data MIME type. - - The Request content to add to the collection. - The headers to add to the collection. - - - - Frees resources held by the object. - - - - - - - - - - - - - - - - - - - - - Attempts to compute the length of the underlying content, if available. - - The length of the underlying data. - - - - Provides a container for content encoded using multipart/form-data MIME type. - - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the class. - - The boundary string for the multipart form data content. - - - - Add HTTP content to a collection of RequestContent objects that - get serialized to multipart/form-data MIME type. - - The Request content to add to the collection. - - - - Add HTTP content to a collection of RequestContent objects that - get serialized to multipart/form-data MIME type. - - The Request content to add to the collection. - The headers to add to the collection. - - - - Add HTTP content to a collection of RequestContent objects that - get serialized to multipart/form-data MIME type. - - The Request content to add to the collection. - The name for the request content to add. - The headers to add to the collection. - - - - Add HTTP content to a collection of RequestContent objects that - get serialized to multipart/form-data MIME type. - - The Request content to add to the collection. - The name for the request content to add. - The file name for the request content to add to the collection. - The headers to add to the collection. - - - - Helper for interacting with AppConfig settings and their related Environment variable settings. - - - - - Determines if either an AppContext switch or its corresponding Environment Variable is set - - Name of the AppContext switch. - Name of the Environment variable. - If the AppContext switch has been set, returns the value of the switch. - If the AppContext switch has not been set, returns the value of the environment variable. - False if neither is set. - - - - - Argument validation. - - - This class should be shared via source using Azure.Core.props and contain only common argument validation. - It is declared partial so that you can use the same familiar class name but extend it with project-specific validation. - To extend the functionality of this class, just declare your own partial class with project-specific methods. - - - Be sure to document exceptions thrown by these methods on your public methods. - - - - - - Throws if is null. - - The value to validate. - The name of the parameter. - is null. - - - - Throws if has not been initialized. - - The value to validate. - The name of the parameter. - has not been initialized. - - - - Throws if is null or an empty collection. - - The value to validate. - The name of the parameter. - is an empty collection. - is null. - - - - Throws if is null or an empty string. - - The value to validate. - The name of the parameter. - is an empty string. - is null. - - - - Throws if is null, an empty string, or consists only of white-space characters. - - The value to validate. - The name of the parameter. - is an empty string or consists only of white-space characters. - is null. - - - - Throws if is the default value for type . - - The type of structure to validate which implements . - The value to validate. - The name of the parameter. - is the default value for type . - - - - Throws if is less than the or greater than the . - - The type of to validate which implements . - The value to validate. - The minimum value to compare. - The maximum value to compare. - The name of the parameter. - - - - Throws if is not defined for . - - The type to validate against. - The value to validate. - The name of the parameter. - is not defined for . - - - - Throws if has not been initialized; otherwise, returns . - - The value to validate. - The name of the parameter. - has not been initialized. - - - - Throws if is null or an empty string; otherwise, returns . - - The value to validate. - The name of the parameter. - is an empty string. - is null. - - - - Throws if is not null. - - The value to validate. - The name of the parameter. - The error message. - is not null. - - - - Primitive that combines async lock and value cache - - - - - - Method that either returns cached value or acquire a lock. - If one caller has acquired a lock, other callers will be waiting for the lock to be released. - If value is set, lock is released and all waiters get that value. - If value isn't set, the next waiter in the queue will get the lock. - - - - - - - - Set value to the cache and to all the waiters - - - - - - - Release the lock and allow next waiter acquire it - - - - - Returns true if lock contains the cached value. Otherwise false. - - - - - Returns cached value if it was set when lock has been created. Throws exception otherwise. - - Value isn't set. - - - - Set value to the cache and to all the waiters. - - - Value is set already. - - - - Initializes a new instance of the class. - - The customer provided client options object. - Flag controlling if - created by this for client method calls should be suppressed when called - by other Azure SDK client methods. It's recommended to set it to true for new clients; use default (null) - for backward compatibility reasons, or set it to false to explicitly disable suppression for specific cases. - The default value could change in the future, the flag should be only set to false if suppression for the client - should never be enabled. - - - - Initializes a new instance of the class. - - Namespace of the client class, such as Azure.Storage or Azure.AppConfiguration. - Azure Resource Provider namespace of the Azure service SDK is primarily used for. - The customer provided client diagnostics options. - Flag controlling if - created by this for client method calls should be suppressed when called - by other Azure SDK client methods. It's recommended to set it to true for new clients, use default (null) for old clients - for backward compatibility reasons, or set it to false to explicitly disable suppression for specific cases. - The default value could change in the future, the flag should be only set to false if suppression for the client - should never be enabled. - - - - Adds a link to the scope. This must be called before has been called for the DiagnosticScope. - - The traceparent for the link. - The tracestate for the link. - Optional attributes to associate with the link. - - - - Sets the trace context for the current scope. - - The trace parent to set for the current scope. - The trace state to set for the current scope. - - - - Marks the scope as failed. - - The exception to associate with the failed scope. - - - - Marks the scope as failed with low-cardinality error.type attribute. - - Error code to associate with the failed scope. - - - - Until Activity Source is no longer considered experimental. - - - - - Creates diagnostic scope factory. - - The namespace which is used as a prefix for all ActivitySources created by the factory and the name of DiagnosticSource (when used). - Azure resource provider namespace. - Flag indicating if distributed tracing is enabled. - Flag indicating if nested Azure SDK activities describing public API calls should be suppressed. - Whether instrumentation is considered stable. When false, experimental feature flag controls if tracing is enabled. - - - - This method combines client namespace and operation name into an ActivitySource name and creates the activity source. - For example: - ns: Azure.Storage.Blobs - name: BlobClient.DownloadTo - result Azure.Storage.Blobs.BlobClient - - - - - Both and are defined as public structs so that foreach can use duck typing - to call and avoid heap memory allocation. - Please don't delete this method and don't make these types private. - - - - - - A delay strategy that uses a fixed delay with no jitter applied. This is used by data plane LROs. - - - - - Marks methods that call methods on other client and don't need their diagnostics verified. - - - - - Creates a new instance of . - - - - - Creates a new instance of . - - Sets whether or not diagnostic scope validation should happen. - - - - Gets whether or not we should validate DiagnosticScope for this API. - In the case where there is an internal API that makes the Azure API call and a public API that uses it we need ForwardsClientCalls. - If the public API will cache the results then the diagnostic scope will not always be created because an Azure API is not always called. - In this case we need to turn off this validation for this API only. - - - - - This function is used to get the final request uri after the lro has completed. - - - - - A helper class used to build long-running operation instances. In order to use this helper: - - Make sure your LRO implements the interface. - Add a private field to your LRO, and instantiate it during construction. - Delegate method calls to the implementations. - - Supported members: - - - - - - , used for - - - - - - - - - - - - - - - - - - - Initializes a new instance of the class in a final successful state. - - The final value of . - - - - Initializes a new instance of the class in a final failed state. - - The final value of . - The exception that will be thrown by UpdateStatusAsync. - - - - Initializes a new instance of the class. - - The long-running operation making use of this class. Passing "this" is expected. - Used for diagnostic scope and exception creation. This is expected to be the instance created during the construction of your main client. - - The initial value of . Usually, long-running operation objects can be instantiated in two ways: - - - When calling a client's "Start<OperationName>" method, a service call is made to start the operation, and an instance is returned. - In this case, the response received from this service call can be passed here. - - - When a user instantiates an directly using a public constructor, there's no previous service call. In this case, passing null is expected. - - - - - The type name of the long-running operation making use of this class. Used when creating diagnostic scopes. If left null, the type name will be inferred based on the - parameter . - - The attributes to use during diagnostic scope creation. - The delay strategy to use. Default is . - - - - An interface used by for making service calls and updating state. It's expected that - your long-running operation classes implement this interface. - - - - - Calls the service and updates the state of the long-running operation. Properties directly handled by the - class, such as - don't need to be updated. Operation-specific properties, such as "CreateOn" or "LastModified", - must be manually updated by the operation implementing this method. - Usage example: - - async ValueTask<OperationState> IOperation.UpdateStateAsync(bool async, CancellationToken cancellationToken)
- {
- Response<R> response = async ? <async service call> : <sync service call>;
- if (<operation succeeded>) return OperationState.Success(response.GetRawResponse(), <parse response>);
- if (<operation failed>) return OperationState.Failure(response.GetRawResponse());
- return OperationState.Pending(response.GetRawResponse());
- } -
-
-
- true if the call should be executed asynchronously. Otherwise, false. - A controlling the request lifetime. - - A structure indicating the current operation state. The structure must be instantiated by one of - its static methods: - - Use when the operation has completed successfully. - Use when the operation has completed with failures. - Use when the operation has not completed yet. - - -
- - - A helper structure passed to to indicate the current operation state. This structure must be - instantiated by one of its static methods, depending on the operation state: - - Use when the operation has completed successfully. - Use when the operation has completed with failures. - Use when the operation has not completed yet. - - - - - - Instantiates an indicating the operation has completed successfully. - - The HTTP response obtained during the status update. - A new instance. - Thrown if is null. - - - - Instantiates an indicating the operation has completed with failures. - - The HTTP response obtained during the status update. - - The exception to throw from UpdateStatus because of the operation failure. If left null, - a default exception is created based on the parameter. - - A new instance. - Thrown if is null. - - - - Instantiates an indicating the operation has not completed yet. - - The HTTP response obtained during the status update. - A new instance. - Thrown if is null. - - - - The last HTTP response received from the server. Its update already handled in calls to "UpdateStatus" and - "WaitForCompletionAsync", but custom methods not supported by this class, such as "CancelOperation", - must update it as well. - Usage example: - - public Response GetRawResponse() => _operationInternal.RawResponse; - - - - - - - Returns true if the long-running operation has completed. - Usage example: - - public bool HasCompleted => _operationInternal.HasCompleted; - - - - - - - Calls the server to get the latest status of the long-running operation, handling diagnostic scope creation for distributed - tracing. The default scope name can be changed with the "operationTypeName" parameter passed to the constructor. - Usage example: - - public async ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken) => - await _operationInternal.UpdateStatusAsync(cancellationToken).ConfigureAwait(false); - - - - A controlling the request lifetime. - The HTTP response received from the server. - - After a successful run, this method will update and might update . - - Thrown if there's been any issues during the connection, or if the operation has completed with failures. - - - - Calls the server to get the latest status of the long-running operation, handling diagnostic scope creation for distributed - tracing. The default scope name can be changed with the "operationTypeName" parameter passed to the constructor. - Usage example: - - public Response UpdateStatus(CancellationToken cancellationToken) => _operationInternal.UpdateStatus(cancellationToken); - - - - A controlling the request lifetime. - The HTTP response received from the server. - - After a successful run, this method will update and might update . - - Thrown if there's been any issues during the connection, or if the operation has completed with failures. - - - - Periodically calls until the long-running operation completes. - After each service call, a retry-after header may be returned to communicate that there is no reason to poll - for status change until the specified time has passed. The maximum of the retry after value and the fallback strategy - is then used as the wait interval. - Headers supported are: "Retry-After", "retry-after-ms", and "x-ms-retry-after-ms", - Usage example: - - public async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken) => - await _operationInternal.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - - - - A controlling the request lifetime. - The last HTTP response received from the server, including the final result of the long-running operation. - Thrown if there's been any issues during the connection, or if the operation has completed with failures. - - - - Periodically calls until the long-running operation completes. The interval - between calls is defined by the parameter , but it can change based on information returned - from the server. After each service call, a retry-after header may be returned to communicate that there is no reason to poll - for status change until the specified time has passed. In this case, the maximum value between the - parameter and the retry-after header is chosen as the wait interval. Headers supported are: "Retry-After", "retry-after-ms", - and "x-ms-retry-after-ms". - Usage example: - - public async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) => - await _operationInternal.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false); - - - - The interval between status requests to the server. - A controlling the request lifetime. - The last HTTP response received from the server, including the final result of the long-running operation. - Thrown if there's been any issues during the connection, or if the operation has completed with failures. - - - - Periodically calls until the long-running operation completes. - After each service call, a retry-after header may be returned to communicate that there is no reason to poll - for status change until the specified time has passed. The maximum of the retry after value and the fallback strategy - is then used as the wait interval. - Headers supported are: "Retry-After", "retry-after-ms", and "x-ms-retry-after-ms", - and "x-ms-retry-after-ms". - Usage example: - - public async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) => - await _operationInternal.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false); - - - - A controlling the request lifetime. - The last HTTP response received from the server, including the final result of the long-running operation. - Thrown if there's been any issues during the connection, or if the operation has completed with failures. - - - - Periodically calls until the long-running operation completes. The interval - between calls is defined by the parameter , but it can change based on information returned - from the server. After each service call, a retry-after header may be returned to communicate that there is no reason to poll - for status change until the specified time has passed. In this case, the maximum value between the - parameter and the retry-after header is chosen as the wait interval. Headers supported are: "Retry-After", "retry-after-ms", - and "x-ms-retry-after-ms". - Usage example: - - public async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) => - await _operationInternal.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false); - - - - The interval between status requests to the server. - A controlling the request lifetime. - The last HTTP response received from the server, including the final result of the long-running operation. - Thrown if there's been any issues during the connection, or if the operation has completed with failures. - - - - A helper class used to build long-running operation instances. In order to use this helper: - - Make sure your LRO implements the interface. - Add a private field to your LRO, and instantiate it during construction. - Delegate method calls to the implementations. - - Supported members: - - - - - - - - - - - - , used for - - - - - - - - - - - - - - - - The final result of the long-running operation. Must match the type used in . - - - - Initializes a new instance of the class in a final successful state. - - The final value of . - The final result of the long-running operation. - - - - Initializes a new instance of the class in a final failed state. - - The final value of . - The exception that will be thrown by UpdateStatusAsync. - - - - Initializes a new instance of the class. - - The long-running operation making use of this class. Passing "this" is expected. - Used for diagnostic scope and exception creation. This is expected to be the instance created during the construction of your main client. - - The initial value of . Usually, long-running operation objects can be instantiated in two ways: - - - When calling a client's "Start<OperationName>" method, a service call is made to start the operation, and an instance is returned. - In this case, the response received from this service call can be passed here. - - - When a user instantiates an directly using a public constructor, there's no previous service call. In this case, passing null is expected. - - - - - The type name of the long-running operation making use of this class. Used when creating diagnostic scopes. If left null, the type name will be inferred based on the - parameter . - - The attributes to use during diagnostic scope creation. - The delay strategy when Retry-After header is not present. When it is present, the longer of the two delays will be used. - Default is . - - - - Returns true if the long-running operation completed successfully and has produced a final result. - Usage example: - - public bool HasValue => _operationInternal.HasValue; - - - - - - - The final result of the long-running operation. - Usage example: - - public T Value => _operationInternal.Value; - - - - Thrown when the operation has not completed yet. - Thrown when the operation has completed with failures. - - - - Periodically calls until the long-running operation completes. - After each service call, a retry-after header may be returned to communicate that there is no reason to poll - for status change until the specified time has passed. - Headers supported are: "Retry-After", "retry-after-ms", and "x-ms-retry-after-ms", - Usage example: - - public async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken) => - await _operationInternal.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - - - - A controlling the request lifetime. - The last HTTP response received from the server, including the final result of the long-running operation. - Thrown if there's been any issues during the connection, or if the operation has completed with failures. - - - - Periodically calls until the long-running operation completes. The interval - between calls is defined by the parameter , but it can change based on information returned - from the server. After each service call, a retry-after header may be returned to communicate that there is no reason to poll - for status change until the specified time has passed. In this case, the maximum value between the - parameter and the retry-after header is chosen as the wait interval. Headers supported are: "Retry-After", "retry-after-ms", - and "x-ms-retry-after-ms". - Usage example: - - public async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) => - await _operationInternal.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false); - - - - The interval between status requests to the server. - A controlling the request lifetime. - The last HTTP response received from the server, including the final result of the long-running operation. - Thrown if there's been any issues during the connection, or if the operation has completed with failures. - - - - Periodically calls until the long-running operation completes. - After each service call, a retry-after header may be returned to communicate that there is no reason to poll - for status change until the specified time has passed. - Headers supported are: "Retry-After", "retry-after-ms", and "x-ms-retry-after-ms", - Usage example: - - public async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken) => - await _operationInternal.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - - - - A controlling the request lifetime. - The last HTTP response received from the server, including the final result of the long-running operation. - Thrown if there's been any issues during the connection, or if the operation has completed with failures. - - - - Periodically calls until the long-running operation completes. The interval - between calls is defined by the , which takes into account any retry-after header that is returned - from the server. - Usage example: - - public async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken) => - await _operationInternal.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); - - - - The interval between status requests to the server. - A controlling the request lifetime. - The last HTTP response received from the server, including the final result of the long-running operation. - Thrown if there's been any issues during the connection, or if the operation has completed with failures. - - - - An interface used by for making service calls and updating state. It's expected that - your long-running operation classes implement this interface. - - The final result of the long-running operation. Must match the type used in . - - - - Calls the service and updates the state of the long-running operation. Properties directly handled by the - class, such as or - , don't need to be updated. Operation-specific properties, such - as "CreateOn" or "LastModified", must be manually updated by the operation implementing this - method. - Usage example: - - async ValueTask<OperationState<T>> IOperation<T>.UpdateStateAsync(bool async, CancellationToken cancellationToken)
- {
- Response<R> response = async ? <async service call> : <sync service call>;
- if (<operation succeeded>) return OperationState<T>.Success(response.GetRawResponse(), <parse response>);
- if (<operation failed>) return OperationState<T>.Failure(response.GetRawResponse());
- return OperationState<T>.Pending(response.GetRawResponse());
- } -
-
-
- true if the call should be executed asynchronously. Otherwise, false. - A controlling the request lifetime. - - A structure indicating the current operation state. The structure must be instantiated by one of - its static methods: - - Use when the operation has completed successfully. - Use when the operation has completed with failures. - Use when the operation has not completed yet. - - -
- - - A helper structure passed to to indicate the current operation state. This structure must be - instantiated by one of its static methods, depending on the operation state: - - Use when the operation has completed successfully. - Use when the operation has completed with failures. - Use when the operation has not completed yet. - - - The final result of the long-running operation. Must match the type used in . - - - - Instantiates an indicating the operation has completed successfully. - - The HTTP response obtained during the status update. - The final result of the long-running operation. - A new instance. - Thrown if or is null. - - - - Instantiates an indicating the operation has completed with failures. - - The HTTP response obtained during the status update. - - The exception to throw from UpdateStatus because of the operation failure. The same exception will be thrown when - is called. If left null, a default exception is created based on the - parameter. - - A new instance. - Thrown if is null. - - - - Instantiates an indicating the operation has not completed yet. - - The HTTP response obtained during the status update. - A new instance. - Thrown if is null. - - - - Implementation of LRO polling logic. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A delay strategy that uses a fixed sequence of delays with no jitter applied. This is used by management LROs. - - - - - Gets or sets the method name to use when serializing the property value (property name excluded) - The signature of the serialization hook method must be or compatible with when invoking: - private void SerializeHook(Utf8JsonWriter writer); - - - - - Gets or sets the method name to use when deserializing the property value from the JSON - private static void DeserializationHook(JsonProperty property, ref TypeOfTheProperty propertyValue); // if the property is required - private static void DeserializationHook(JsonProperty property, ref Optional<TypeOfTheProperty> propertyValue); // if the property is optional - - - - - Gets or sets a coma separated list of additional model usage modes. Allowed values: model, error, intput, output. - - - - - Gets or sets a coma separated list of additional model serialization formats. - - - - - - - JsonConverter for managed service identity type v3. - - - Serialize managed service identity type to v3 format. - The writer. - The ManagedServiceIdentityType model which is v4. - The options for JsonSerializer. - - - Deserialize managed service identity type from v3 format. - The reader. - The type to convert - The options for JsonSerializer. - - - - helper class - - - - - Collects the segments in a resource identifier into a string - - the resource identifier - - - - - An extension method for supporting replacing one dictionary content with another one. - This is used to support resource tags. - - The destination dictionary in which the content will be replaced. - The source dictionary from which the content is copied from. - The destination dictionary that has been altered. - - - - Indicates that the specified method requires the ability to generate new code at runtime, - for example through . - - - This allows tools to understand which methods are unsafe to call when compiling ahead of time. - - - - - Initializes a new instance of the class - with the specified message. - - - A message that contains information about the usage of dynamic code. - - - - - Gets a message that contains information about the usage of dynamic code. - - - - - Gets or sets an optional URL that contains more information about the method, - why it requires dynamic code, and what options a consumer has to deal with it. - - - - - Indicates that the specified method requires dynamic access to code that is not referenced - statically, for example through . - - - This allows tools to understand which methods are unsafe to call when removing unreferenced - code from an application. - - - - - Initializes a new instance of the class - with the specified message. - - - A message that contains information about the usage of unreferenced code. - - - - - Gets a message that contains information about the usage of unreferenced code. - - - - - Gets or sets an optional URL that contains more information about the method, - why it requires unreferenced code, and what options a consumer has to deal with it. - - - - - Suppresses reporting of a specific rule violation, allowing multiple suppressions on a - single code artifact. - - - is different than - in that it doesn't have a - . So it is always preserved in the compiled assembly. - - - - - Initializes a new instance of the - class, specifying the category of the tool and the identifier for an analysis rule. - - The category for the attribute. - The identifier of the analysis rule the attribute applies to. - - - - Gets the category identifying the classification of the attribute. - - - The property describes the tool or tool analysis category - for which a message suppression attribute applies. - - - - - Gets the identifier of the analysis tool rule to be suppressed. - - - Concatenated together, the and - properties form a unique check identifier. - - - - - Gets or sets the scope of the code that is relevant for the attribute. - - - The Scope property is an optional argument that specifies the metadata scope for which - the attribute is relevant. - - - - - Gets or sets a fully qualified path that represents the target of the attribute. - - - The property is an optional argument identifying the analysis target - of the attribute. An example value is "System.IO.Stream.ctor():System.Void". - Because it is fully qualified, it can be long, particularly for targets such as parameters. - The analysis tool user interface should be capable of automatically formatting the parameter. - - - - - Gets or sets an optional argument expanding on exclusion criteria. - - - The property is an optional argument that specifies additional - exclusion where the literal metadata target is not sufficiently precise. For example, - the cannot be applied within a method, - and it may be desirable to suppress a violation against a statement in the method that will - give a rule violation, but not against all statements in the method. - - - - - Gets or sets the justification for suppressing the code analysis message. - - - - - States a dependency that one member has on another. - - - This can be used to inform tooling of a dependency that is otherwise not evident purely from - metadata and IL, for example a member relied on via reflection. - - - - - Initializes a new instance of the class - with the specified signature of a member on the same type as the consumer. - - The signature of the member depended on. - - - - Initializes a new instance of the class - with the specified signature of a member on a . - - The signature of the member depended on. - The containing . - - - - Initializes a new instance of the class - with the specified signature of a member on a type in an assembly. - - The signature of the member depended on. - The full name of the type containing the specified member. - The assembly name of the type containing the specified member. - - - - Initializes a new instance of the class - with the specified types of members on a . - - The types of members depended on. - The containing the specified members. - - - - Initializes a new instance of the class - with the specified types of members on a type in an assembly. - - The types of members depended on. - The full name of the type containing the specified members. - The assembly name of the type containing the specified members. - - - - Gets the signature of the member depended on. - - - Either must be a valid string or - must not equal , but not both. - - - - - Gets the which specifies the type - of members depended on. - - - Either must be a valid string or - must not equal , but not both. - - - - - Gets the containing the specified member. - - - If neither nor are specified, - the type of the consumer is assumed. - - - - - Gets the full name of the type containing the specified member. - - - If neither nor are specified, - the type of the consumer is assumed. - - - - - Gets the assembly name of the specified type. - - - is only valid when is specified. - - - - - Gets or sets the condition in which the dependency is applicable, e.g. "DEBUG". - - - - - Indicates that certain members on a specified are accessed dynamically, - for example through . - - - This allows tools to understand which members are being accessed during the execution - of a program. - - This attribute is valid on members whose type is or . - - When this attribute is applied to a location of type , the assumption is - that the string represents a fully qualified type name. - - When this attribute is applied to a class, interface, or struct, the members specified - can be accessed dynamically on instances returned from calling - on instances of that class, interface, or struct. - - If the attribute is applied to a method it's treated as a special case and it implies - the attribute should be applied to the "this" parameter of the method. As such the attribute - should only be used on instance methods of types assignable to System.Type (or string, but no methods - will use it there). - - - - - Initializes a new instance of the class - with the specified member types. - - The types of members dynamically accessed. - - - - Gets the which specifies the type - of members dynamically accessed. - - - - - Specifies the types of members that are dynamically accessed. - - This enumeration has a attribute that allows a - bitwise combination of its member values. - - - - - Specifies no members. - - - - - Specifies the default, parameterless public constructor. - - - - - Specifies all public constructors. - - - - - Specifies all non-public constructors. - - - - - Specifies all public methods. - - - - - Specifies all non-public methods. - - - - - Specifies all public fields. - - - - - Specifies all non-public fields. - - - - - Specifies all public nested types. - - - - - Specifies all non-public nested types. - - - - - Specifies all public properties. - - - - - Specifies all non-public properties. - - - - - Specifies all public events. - - - - - Specifies all non-public events. - - - - - Specifies all interfaces implemented by the type. - - - - - Specifies all members. - - -
-
diff --git a/test/TestProjects/MgmtCustomizations/Generated/ArmMgmtCustomizationsModelFactory.cs b/test/TestProjects/MgmtCustomizations/Generated/ArmMgmtCustomizationsModelFactory.cs index 7520e284774..a449b71833b 100644 --- a/test/TestProjects/MgmtCustomizations/Generated/ArmMgmtCustomizationsModelFactory.cs +++ b/test/TestProjects/MgmtCustomizations/Generated/ArmMgmtCustomizationsModelFactory.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Linq; using Azure.Core; using Azure.ResourceManager.Models; @@ -50,13 +49,11 @@ public static Pet Pet(string name = null, int size = default, DateTimeOffset? da /// Despite in the swagger it has a type of string, in the real payload of this request, the service is actually sending using a number, therefore the type in this swagger here is wrong and we have to fix it using customization code. /// /// Pet date of birth. - /// A cat can sleep. - /// A cat can jump. /// A cat can meow. /// A new instance for mocking. - public static Cat Cat(string name = null, int size = default, DateTimeOffset? dateOfBirth = null, string sleep = null, string jump = null, string meow = null) + public static Cat Cat(string name = null, int size = default, DateTimeOffset? dateOfBirth = null, string meow = null) { - return new Cat(PetKind.Cat, name, size, dateOfBirth, sleep, jump, meow); + return new Cat(PetKind.Cat, name, size, dateOfBirth, meow); } /// Initializes a new instance of . @@ -66,43 +63,11 @@ public static Cat Cat(string name = null, int size = default, DateTimeOffset? da /// Despite in the swagger it has a type of string, in the real payload of this request, the service is actually sending using a number, therefore the type in this swagger here is wrong and we have to fix it using customization code. /// /// Pet date of birth. - /// A dog can sleep. /// A dog can bark. - /// A dog can jump. /// A new instance for mocking. - public static Dog Dog(string name = null, int size = default, DateTimeOffset? dateOfBirth = null, string sleep = null, string bark = null, string jump = null) + public static Dog Dog(string name = null, int size = default, DateTimeOffset? dateOfBirth = null, string bark = null) { - return new Dog(PetKind.Dog, name, size, dateOfBirth, sleep, bark, jump); - } - - /// Initializes a new instance of Cat. - /// The name of the pet. - /// - /// The size of the pet. This property here is mocking the following scenario: - /// Despite in the swagger it has a type of string, in the real payload of this request, the service is actually sending using a number, therefore the type in this swagger here is wrong and we have to fix it using customization code. - /// - /// Pet date of birth. - /// A cat can meow. - /// A new instance for mocking. - [EditorBrowsable(EditorBrowsableState.Never)] - public static Cat Cat(string name, int size, DateTimeOffset? dateOfBirth, string meow) - { - return Cat(name, size, dateOfBirth, default, default, meow); - } - - /// Initializes a new instance of Dog. - /// The name of the pet. - /// - /// The size of the pet. This property here is mocking the following scenario: - /// Despite in the swagger it has a type of string, in the real payload of this request, the service is actually sending using a number, therefore the type in this swagger here is wrong and we have to fix it using customization code. - /// - /// Pet date of birth. - /// A dog can bark. - /// A new instance for mocking. - [EditorBrowsable(EditorBrowsableState.Never)] - public static Dog Dog(string name, int size, DateTimeOffset? dateOfBirth, string bark) - { - return Dog(name, size, dateOfBirth, default, bark, default); + return new Dog(PetKind.Dog, name, size, dateOfBirth, bark); } } } diff --git a/test/TestProjects/MgmtCustomizations/Generated/CodeModel.yaml b/test/TestProjects/MgmtCustomizations/Generated/CodeModel.yaml index 9ec3ccf2ec1..85c951c6f18 100644 --- a/test/TestProjects/MgmtCustomizations/Generated/CodeModel.yaml +++ b/test/TestProjects/MgmtCustomizations/Generated/CodeModel.yaml @@ -23,7 +23,7 @@ schemas: !Schemas name: String description: simple string protocol: !Protocols {} - - !StringSchema &ref_34 + - !StringSchema &ref_30 type: string apiVersions: - !ApiVersion @@ -36,7 +36,7 @@ schemas: !Schemas name: String description: '' protocol: !Protocols {} - - !StringSchema &ref_31 + - !StringSchema &ref_27 type: string apiVersions: - !ApiVersion @@ -76,7 +76,7 @@ schemas: !Schemas name: PetStoreType description: The resource type of this pet store protocol: !Protocols {} - - !StringSchema &ref_16 + - !StringSchema &ref_12 type: string apiVersions: - !ApiVersion @@ -86,7 +86,7 @@ schemas: !Schemas name: PetName description: The name of the pet protocol: !Protocols {} - - !StringSchema &ref_17 + - !StringSchema &ref_13 type: string apiVersions: - !ApiVersion @@ -100,7 +100,7 @@ schemas: !Schemas Despite in the swagger it has a type of string, in the real payload of this request, the service is actually sending using a number, therefore the type in this swagger here is wrong and we have to fix it using customization code. protocol: !Protocols {} - - !StringSchema &ref_18 + - !StringSchema &ref_14 type: string apiVersions: - !ApiVersion @@ -110,7 +110,7 @@ schemas: !Schemas name: PetDateOfBirth description: Pet date of birth protocol: !Protocols {} - - !StringSchema &ref_21 + - !StringSchema &ref_17 type: string apiVersions: - !ApiVersion @@ -120,7 +120,7 @@ schemas: !Schemas name: ErrorDetailCode description: The error code. protocol: !Protocols {} - - !StringSchema &ref_22 + - !StringSchema &ref_18 type: string apiVersions: - !ApiVersion @@ -130,7 +130,7 @@ schemas: !Schemas name: ErrorDetailMessage description: The error message. protocol: !Protocols {} - - !StringSchema &ref_23 + - !StringSchema &ref_19 type: string apiVersions: - !ApiVersion @@ -140,7 +140,7 @@ schemas: !Schemas name: ErrorDetailTarget description: The error target. protocol: !Protocols {} - - !StringSchema &ref_25 + - !StringSchema &ref_21 type: string apiVersions: - !ApiVersion @@ -151,26 +151,6 @@ schemas: !Schemas description: The additional info type. protocol: !Protocols {} - !StringSchema &ref_6 - type: string - apiVersions: - - !ApiVersion - version: '2020-06-01' - language: !Languages - default: - name: CatSleep - description: A cat can sleep - protocol: !Protocols {} - - !StringSchema &ref_7 - type: string - apiVersions: - - !ApiVersion - version: '2020-06-01' - language: !Languages - default: - name: CatJump - description: A cat can jump - protocol: !Protocols {} - - !StringSchema &ref_8 type: string apiVersions: - !ApiVersion @@ -180,17 +160,7 @@ schemas: !Schemas name: CatMeow description: A cat can meow protocol: !Protocols {} - - !StringSchema &ref_9 - type: string - apiVersions: - - !ApiVersion - version: '2020-06-01' - language: !Languages - default: - name: DogSleep - description: A dog can sleep - protocol: !Protocols {} - - !StringSchema &ref_10 + - !StringSchema &ref_7 type: string apiVersions: - !ApiVersion @@ -200,18 +170,8 @@ schemas: !Schemas name: DogBark description: A dog can bark protocol: !Protocols {} - - !StringSchema &ref_11 - type: string - apiVersions: - - !ApiVersion - version: '2020-06-01' - language: !Languages - default: - name: DogJump - description: A dog can jump - protocol: !Protocols {} sealedChoices: - - !SealedChoiceSchema &ref_14 + - !SealedChoiceSchema &ref_10 choices: - !ChoiceValue value: Cat @@ -236,7 +196,7 @@ schemas: !Schemas description: The kind of the pet protocol: !Protocols {} constants: - - !ConstantSchema &ref_32 + - !ConstantSchema &ref_28 type: constant value: !ConstantValue value: '2020-06-01' @@ -246,7 +206,7 @@ schemas: !Schemas name: ApiVersion20200601 description: Api Version (2020-06-01) protocol: !Protocols {} - - !ConstantSchema &ref_37 + - !ConstantSchema &ref_33 type: constant value: !ConstantValue value: application/json @@ -256,7 +216,7 @@ schemas: !Schemas name: Accept description: 'Accept: application/json' protocol: !Protocols {} - - !ConstantSchema &ref_43 + - !ConstantSchema &ref_39 type: constant value: !ConstantValue value: application/json @@ -267,7 +227,7 @@ schemas: !Schemas description: Content Type 'application/json' protocol: !Protocols {} anyObjects: - - !AnyObjectSchema &ref_26 + - !AnyObjectSchema &ref_22 type: any-object language: !Languages default: @@ -275,19 +235,19 @@ schemas: !Schemas description: Any object protocol: !Protocols {} objects: - - !ObjectSchema &ref_39 + - !ObjectSchema &ref_35 type: object apiVersions: - !ApiVersion version: '2020-06-01' properties: - !Property - schema: !ArraySchema &ref_28 + schema: !ArraySchema &ref_24 type: array apiVersions: - !ApiVersion version: '2020-06-01' - elementType: !ObjectSchema &ref_19 + elementType: !ObjectSchema &ref_15 type: object apiVersions: - !ApiVersion @@ -321,7 +281,7 @@ schemas: !Schemas description: The resource type of this pet store protocol: !Protocols {} - !Property - schema: !ObjectSchema &ref_20 + schema: !ObjectSchema &ref_16 type: object apiVersions: - !ApiVersion @@ -343,7 +303,7 @@ schemas: !Schemas version: '2020-06-01' children: !Relations all: - - !ObjectSchema &ref_12 + - !ObjectSchema &ref_8 type: object apiVersions: - !ApiVersion @@ -357,22 +317,6 @@ schemas: !Schemas properties: - !Property schema: *ref_6 - serializedName: sleep - language: !Languages - default: - name: sleep - description: A cat can sleep - protocol: !Protocols {} - - !Property - schema: *ref_7 - serializedName: jump - language: !Languages - default: - name: jump - description: A cat can jump - protocol: !Protocols {} - - !Property - schema: *ref_8 readOnly: true serializedName: meow language: !Languages @@ -393,7 +337,7 @@ schemas: !Schemas description: A cat namespace: '' protocol: !Protocols {} - - !ObjectSchema &ref_13 + - !ObjectSchema &ref_9 type: object apiVersions: - !ApiVersion @@ -406,29 +350,13 @@ schemas: !Schemas - *ref_5 properties: - !Property - schema: *ref_9 - serializedName: sleep - language: !Languages - default: - name: sleep - description: A dog can sleep - protocol: !Protocols {} - - !Property - schema: *ref_10 + schema: *ref_7 serializedName: bark language: !Languages default: name: bark description: A dog can bark protocol: !Protocols {} - - !Property - schema: *ref_11 - serializedName: jump - language: !Languages - default: - name: jump - description: A dog can jump - protocol: !Protocols {} serializationFormats: - json usage: @@ -443,17 +371,17 @@ schemas: !Schemas namespace: '' protocol: !Protocols {} immediate: - - *ref_12 - - *ref_13 + - *ref_8 + - *ref_9 discriminator: !Discriminator all: - Cat: *ref_12 - Dog: *ref_13 + Cat: *ref_8 + Dog: *ref_9 immediate: - Cat: *ref_12 - Dog: *ref_13 - property: !Property &ref_15 - schema: *ref_14 + Cat: *ref_8 + Dog: *ref_9 + property: !Property &ref_11 + schema: *ref_10 isDiscriminator: true required: true serializedName: kind @@ -463,9 +391,9 @@ schemas: !Schemas description: The kind of the pet protocol: !Protocols {} properties: - - *ref_15 + - *ref_11 - !Property - schema: *ref_16 + schema: *ref_12 readOnly: true required: false serializedName: name @@ -475,7 +403,7 @@ schemas: !Schemas description: The name of the pet protocol: !Protocols {} - !Property - schema: *ref_17 + schema: *ref_13 required: false serializedName: size language: !Languages @@ -488,7 +416,7 @@ schemas: !Schemas using customization code. protocol: !Protocols {} - !Property - schema: *ref_18 + schema: *ref_14 required: false serializedName: dateOfBirth language: !Languages @@ -562,24 +490,24 @@ schemas: !Schemas description: The list result of the rules namespace: '' protocol: !Protocols {} - - *ref_19 - - *ref_20 + - *ref_15 + - *ref_16 - *ref_5 - - !ObjectSchema &ref_40 + - !ObjectSchema &ref_36 type: object apiVersions: - !ApiVersion version: '2020-06-01' properties: - !Property - schema: !ObjectSchema &ref_24 + schema: !ObjectSchema &ref_20 type: object apiVersions: - !ApiVersion version: '2020-06-01' properties: - !Property - schema: *ref_21 + schema: *ref_17 readOnly: true serializedName: code language: !Languages @@ -588,7 +516,7 @@ schemas: !Schemas description: The error code. protocol: !Protocols {} - !Property - schema: *ref_22 + schema: *ref_18 readOnly: true serializedName: message language: !Languages @@ -597,7 +525,7 @@ schemas: !Schemas description: The error message. protocol: !Protocols {} - !Property - schema: *ref_23 + schema: *ref_19 readOnly: true serializedName: target language: !Languages @@ -606,12 +534,12 @@ schemas: !Schemas description: The error target. protocol: !Protocols {} - !Property - schema: !ArraySchema &ref_29 + schema: !ArraySchema &ref_25 type: array apiVersions: - !ApiVersion version: '2020-06-01' - elementType: *ref_24 + elementType: *ref_20 extensions: x-ms-identifiers: - message @@ -633,19 +561,19 @@ schemas: !Schemas description: The error details. protocol: !Protocols {} - !Property - schema: !ArraySchema &ref_30 + schema: !ArraySchema &ref_26 type: array apiVersions: - !ApiVersion version: '2020-06-01' - elementType: !ObjectSchema &ref_27 + elementType: !ObjectSchema &ref_23 type: object apiVersions: - !ApiVersion version: '2020-06-01' properties: - !Property - schema: *ref_25 + schema: *ref_21 readOnly: true serializedName: type language: !Languages @@ -654,7 +582,7 @@ schemas: !Schemas description: The additional info type. protocol: !Protocols {} - !Property - schema: *ref_26 + schema: *ref_22 readOnly: true serializedName: info language: !Languages @@ -716,17 +644,17 @@ schemas: !Schemas namespace: '' summary: Error response protocol: !Protocols {} - - *ref_24 - - *ref_27 - - *ref_12 - - *ref_13 + - *ref_20 + - *ref_23 + - *ref_8 + - *ref_9 arrays: - - *ref_28 - - *ref_29 - - *ref_30 + - *ref_24 + - *ref_25 + - *ref_26 globalParameters: - - !Parameter &ref_35 - schema: *ref_31 + - !Parameter &ref_31 + schema: *ref_27 implementation: Client required: true extensions: @@ -739,7 +667,7 @@ globalParameters: protocol: !Protocols http: !HttpParameter in: path - - !Parameter &ref_33 + - !Parameter &ref_29 schema: *ref_0 clientDefaultValue: https://management.azure.com implementation: Client @@ -755,8 +683,8 @@ globalParameters: protocol: !Protocols http: !HttpParameter in: uri - - !Parameter &ref_36 - schema: *ref_32 + - !Parameter &ref_32 + schema: *ref_28 implementation: Client origin: modelerfour:synthesized/api-version required: true @@ -778,9 +706,9 @@ operationGroups: - !ApiVersion version: '2020-06-01' parameters: - - *ref_33 - - !Parameter &ref_38 - schema: *ref_34 + - *ref_29 + - !Parameter &ref_34 + schema: *ref_30 implementation: Method required: true language: !Languages @@ -791,13 +719,13 @@ operationGroups: protocol: !Protocols http: !HttpParameter in: path - - *ref_35 - - *ref_36 + - *ref_31 + - *ref_32 requests: - !Request parameters: - !Parameter - schema: *ref_37 + schema: *ref_33 implementation: Method origin: modelerfour:synthesized/accept required: true @@ -820,10 +748,10 @@ operationGroups: method: get uri: '{$host}' signatureParameters: - - *ref_38 + - *ref_34 responses: - !SchemaResponse - schema: *ref_39 + schema: *ref_35 language: !Languages default: name: '' @@ -837,7 +765,7 @@ operationGroups: - '200' exceptions: - !SchemaResponse - schema: *ref_40 + schema: *ref_36 language: !Languages default: name: '' @@ -860,9 +788,9 @@ operationGroups: - !ApiVersion version: '2020-06-01' parameters: - - *ref_33 - - !Parameter &ref_41 - schema: *ref_34 + - *ref_29 + - !Parameter &ref_37 + schema: *ref_30 implementation: Method required: true language: !Languages @@ -873,8 +801,8 @@ operationGroups: protocol: !Protocols http: !HttpParameter in: path - - !Parameter &ref_42 - schema: *ref_31 + - !Parameter &ref_38 + schema: *ref_27 implementation: Method required: true language: !Languages @@ -885,13 +813,13 @@ operationGroups: protocol: !Protocols http: !HttpParameter in: path - - *ref_35 - - *ref_36 + - *ref_31 + - *ref_32 requests: - !Request parameters: - !Parameter - schema: *ref_37 + schema: *ref_33 implementation: Method origin: modelerfour:synthesized/accept required: true @@ -914,11 +842,11 @@ operationGroups: method: get uri: '{$host}' signatureParameters: - - *ref_41 - - *ref_42 + - *ref_37 + - *ref_38 responses: - !SchemaResponse - schema: *ref_19 + schema: *ref_15 language: !Languages default: name: '' @@ -932,7 +860,7 @@ operationGroups: - '200' exceptions: - !SchemaResponse - schema: *ref_40 + schema: *ref_36 language: !Languages default: name: '' @@ -955,9 +883,9 @@ operationGroups: - !ApiVersion version: '2020-06-01' parameters: - - *ref_33 - - !Parameter &ref_46 - schema: *ref_34 + - *ref_29 + - !Parameter &ref_42 + schema: *ref_30 implementation: Method required: true language: !Languages @@ -968,8 +896,8 @@ operationGroups: protocol: !Protocols http: !HttpParameter in: path - - !Parameter &ref_47 - schema: *ref_31 + - !Parameter &ref_43 + schema: *ref_27 implementation: Method required: true language: !Languages @@ -980,13 +908,13 @@ operationGroups: protocol: !Protocols http: !HttpParameter in: path - - *ref_35 - - *ref_36 + - *ref_31 + - *ref_32 requestMediaTypes: - application/json: !Request &ref_45 + application/json: !Request &ref_41 parameters: - !Parameter - schema: *ref_43 + schema: *ref_39 implementation: Method origin: modelerfour:synthesized/content-type required: true @@ -998,8 +926,8 @@ operationGroups: protocol: !Protocols http: !HttpParameter in: header - - !Parameter &ref_44 - schema: *ref_19 + - !Parameter &ref_40 + schema: *ref_15 implementation: Method required: true language: !Languages @@ -1011,7 +939,7 @@ operationGroups: in: body style: json - !Parameter - schema: *ref_37 + schema: *ref_33 implementation: Method origin: modelerfour:synthesized/accept required: true @@ -1024,7 +952,7 @@ operationGroups: http: !HttpParameter in: header signatureParameters: - - *ref_44 + - *ref_40 language: !Languages default: name: '' @@ -1038,13 +966,13 @@ operationGroups: - application/json uri: '{$host}' requests: - - *ref_45 + - *ref_41 signatureParameters: - - *ref_46 - - *ref_47 + - *ref_42 + - *ref_43 responses: - !SchemaResponse - schema: *ref_19 + schema: *ref_15 language: !Languages default: name: '' @@ -1057,7 +985,7 @@ operationGroups: statusCodes: - '200' - !SchemaResponse - schema: *ref_19 + schema: *ref_15 language: !Languages default: name: '' @@ -1070,7 +998,7 @@ operationGroups: statusCodes: - '201' - !SchemaResponse - schema: *ref_19 + schema: *ref_15 language: !Languages default: name: '' @@ -1084,7 +1012,7 @@ operationGroups: - '202' exceptions: - !SchemaResponse - schema: *ref_40 + schema: *ref_36 language: !Languages default: name: '' @@ -1109,9 +1037,9 @@ operationGroups: - !ApiVersion version: '2020-06-01' parameters: - - *ref_33 - - !Parameter &ref_48 - schema: *ref_34 + - *ref_29 + - !Parameter &ref_44 + schema: *ref_30 implementation: Method required: true language: !Languages @@ -1122,8 +1050,8 @@ operationGroups: protocol: !Protocols http: !HttpParameter in: path - - !Parameter &ref_49 - schema: *ref_31 + - !Parameter &ref_45 + schema: *ref_27 implementation: Method required: true language: !Languages @@ -1134,13 +1062,13 @@ operationGroups: protocol: !Protocols http: !HttpParameter in: path - - *ref_35 - - *ref_36 + - *ref_31 + - *ref_32 requests: - !Request parameters: - !Parameter - schema: *ref_37 + schema: *ref_33 implementation: Method origin: modelerfour:synthesized/accept required: true @@ -1163,8 +1091,8 @@ operationGroups: method: delete uri: '{$host}' signatureParameters: - - *ref_48 - - *ref_49 + - *ref_44 + - *ref_45 responses: - !Response language: !Languages @@ -1195,7 +1123,7 @@ operationGroups: - '204' exceptions: - !SchemaResponse - schema: *ref_40 + schema: *ref_36 language: !Languages default: name: '' diff --git a/test/TestProjects/MgmtCustomizations/Generated/Models/Cat.Serialization.cs b/test/TestProjects/MgmtCustomizations/Generated/Models/Cat.Serialization.cs index 16eafa10c61..e7bb2edb503 100644 --- a/test/TestProjects/MgmtCustomizations/Generated/Models/Cat.Serialization.cs +++ b/test/TestProjects/MgmtCustomizations/Generated/Models/Cat.Serialization.cs @@ -16,16 +16,6 @@ public partial class Cat : IUtf8JsonSerializable void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); - if (Optional.IsDefined(Sleep)) - { - writer.WritePropertyName("sleep"u8); - writer.WriteStringValue(Sleep); - } - if (Optional.IsDefined(Jump)) - { - writer.WritePropertyName("jump"u8); - writer.WriteStringValue(Jump); - } writer.WritePropertyName("kind"u8); writer.WriteStringValue(Kind.ToSerialString()); if (Optional.IsDefined(Size)) @@ -47,8 +37,6 @@ internal static Cat DeserializeCat(JsonElement element) { return null; } - Optional sleep = default; - Optional jump = default; Optional meow = default; PetKind kind = default; Optional name = default; @@ -56,16 +44,6 @@ internal static Cat DeserializeCat(JsonElement element) Optional dateOfBirth = default; foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("sleep"u8)) - { - sleep = property.Value.GetString(); - continue; - } - if (property.NameEquals("jump"u8)) - { - jump = property.Value.GetString(); - continue; - } if (property.NameEquals("meow"u8)) { meow = property.Value.GetString(); @@ -96,7 +74,7 @@ internal static Cat DeserializeCat(JsonElement element) continue; } } - return new Cat(kind, name.Value, size, Optional.ToNullable(dateOfBirth), sleep.Value, jump.Value, meow.Value); + return new Cat(kind, name.Value, size, Optional.ToNullable(dateOfBirth), meow.Value); } } } diff --git a/test/TestProjects/MgmtCustomizations/Generated/Models/Cat.cs b/test/TestProjects/MgmtCustomizations/Generated/Models/Cat.cs index f9accf535ff..fbf6ffc37a6 100644 --- a/test/TestProjects/MgmtCustomizations/Generated/Models/Cat.cs +++ b/test/TestProjects/MgmtCustomizations/Generated/Models/Cat.cs @@ -26,20 +26,11 @@ public Cat() /// Despite in the swagger it has a type of string, in the real payload of this request, the service is actually sending using a number, therefore the type in this swagger here is wrong and we have to fix it using customization code. /// /// Pet date of birth. - /// A cat can sleep. - /// A cat can jump. /// A cat can meow. - internal Cat(PetKind kind, string name, int size, DateTimeOffset? dateOfBirth, string sleep, string jump, string meow) : base(kind, name, size, dateOfBirth) + internal Cat(PetKind kind, string name, int size, DateTimeOffset? dateOfBirth, string meow) : base(kind, name, size, dateOfBirth) { - Sleep = sleep; - Jump = jump; Meow = meow; Kind = kind; } - - /// A cat can sleep. - public string Sleep { get; set; } - /// A cat can jump. - public string Jump { get; set; } } } diff --git a/test/TestProjects/MgmtCustomizations/Generated/Models/Dog.Serialization.cs b/test/TestProjects/MgmtCustomizations/Generated/Models/Dog.Serialization.cs index 57d1d7f7983..85ad6ac1312 100644 --- a/test/TestProjects/MgmtCustomizations/Generated/Models/Dog.Serialization.cs +++ b/test/TestProjects/MgmtCustomizations/Generated/Models/Dog.Serialization.cs @@ -16,16 +16,6 @@ public partial class Dog : IUtf8JsonSerializable void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); - if (Optional.IsDefined(Sleep)) - { - writer.WritePropertyName("sleep"u8); - writer.WriteStringValue(Sleep); - } - if (Optional.IsDefined(Jump)) - { - writer.WritePropertyName("jump"u8); - writer.WriteStringValue(Jump); - } writer.WritePropertyName("kind"u8); writer.WriteStringValue(Kind.ToSerialString()); if (Optional.IsDefined(Size)) @@ -58,8 +48,6 @@ internal static Dog DeserializeDog(JsonElement element) { return null; } - Optional sleep = default; - Optional jump = default; PetKind kind = default; Optional name = default; Optional size = default; @@ -67,16 +55,6 @@ internal static Dog DeserializeDog(JsonElement element) Optional bark = default; foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("sleep"u8)) - { - sleep = property.Value.GetString(); - continue; - } - if (property.NameEquals("jump"u8)) - { - jump = property.Value.GetString(); - continue; - } if (property.NameEquals("kind"u8)) { kind = property.Value.GetString().ToPetKind(); @@ -131,7 +109,7 @@ internal static Dog DeserializeDog(JsonElement element) continue; } } - return new Dog(kind, name.Value, size, Optional.ToNullable(dateOfBirth), sleep.Value, bark.Value, jump.Value); + return new Dog(kind, name.Value, size, Optional.ToNullable(dateOfBirth), bark.Value); } } } diff --git a/test/TestProjects/MgmtCustomizations/Generated/Models/Dog.cs b/test/TestProjects/MgmtCustomizations/Generated/Models/Dog.cs index cfb58eb1043..12eeebbda5a 100644 --- a/test/TestProjects/MgmtCustomizations/Generated/Models/Dog.cs +++ b/test/TestProjects/MgmtCustomizations/Generated/Models/Dog.cs @@ -26,20 +26,11 @@ public Dog() /// Despite in the swagger it has a type of string, in the real payload of this request, the service is actually sending using a number, therefore the type in this swagger here is wrong and we have to fix it using customization code. /// /// Pet date of birth. - /// A dog can sleep. /// A dog can bark. - /// A dog can jump. - internal Dog(PetKind kind, string name, int size, DateTimeOffset? dateOfBirth, string sleep, string bark, string jump) : base(kind, name, size, dateOfBirth) + internal Dog(PetKind kind, string name, int size, DateTimeOffset? dateOfBirth, string bark) : base(kind, name, size, dateOfBirth) { - Sleep = sleep; Bark = bark; - Jump = jump; Kind = kind; } - - /// A dog can sleep. - public string Sleep { get; set; } - /// A dog can jump. - public string Jump { get; set; } } } diff --git a/test/TestProjects/MgmtCustomizations/MgmtCustomizations.json b/test/TestProjects/MgmtCustomizations/MgmtCustomizations.json index 7510f30b3f2..1add1db52f1 100644 --- a/test/TestProjects/MgmtCustomizations/MgmtCustomizations.json +++ b/test/TestProjects/MgmtCustomizations/MgmtCustomizations.json @@ -292,14 +292,6 @@ } ], "properties": { - "sleep": { - "description": "A cat can sleep", - "type": "string" - }, - "jump": { - "description": "A cat can jump", - "type": "string" - }, "meow": { "description": "A cat can meow", "type": "string", @@ -316,17 +308,9 @@ } ], "properties": { - "sleep": { - "description": "A dog can sleep", - "type": "string" - }, "bark": { "description": "A dog can bark", "type": "string" - }, - "jump": { - "description": "A dog can jump", - "type": "string" } } },