diff --git a/readme.md b/readme.md index 232fd568609..6bb9cc2228a 100644 --- a/readme.md +++ b/readme.md @@ -32,7 +32,8 @@ ___ - [Rename a client](#rename-a-client) - [Replace any generated member](#replace-any-generated-member) - [Remove any generated member](#remove-any-generated-member) - - [Change model namespace or accessability in bulk](#change-model-namespace-or-accessability-in-bulk) + - [Change model namespace or accessibility in bulk](#change-model-namespace-or-accessibility-in-bulk) + - [Change operation accessibility in bulk](#change-operation-accessibility-in-bulk) - [Exclude models from namespace](#exclude-models-from-namespace) @@ -918,7 +919,7 @@ namespace Azure.Service.Models -### Change model namespace or accessability in bulk +### Change model namespace or accessibility in bulk
@@ -964,6 +965,34 @@ directive:
+### Change operation accessibility in bulk + +
+ +**Generated code before (Generated/Client.cs):** + +``` C# +public virtual Response Operation(string body = null, CancellationToken cancellationToken = default) +public virtual async Task OperationAsync(string body = null, CancellationToken cancellationToken = default) +``` + +**Add autorest.md transformation** + +``` +directive: +- from: swagger-document + where: $..[?(@.operationId=='Operation')] + transform: > + $["x-accessibility"] = "internal"; +``` + +**Generated code after (Generated/Client.cs):** + +``` C# +internal virtual Response Operation(string body = null, CancellationToken cancellationToken = default) +internal virtual async Task OperationAsync(string body = null, CancellationToken cancellationToken = default) +``` + ### Exclude models from namespace
diff --git a/src/AutoRest.CSharp/Common/Generation/Writers/RequestWriterHelpers.cs b/src/AutoRest.CSharp/Common/Generation/Writers/RequestWriterHelpers.cs index a1a2e92891c..609ca9968c1 100644 --- a/src/AutoRest.CSharp/Common/Generation/Writers/RequestWriterHelpers.cs +++ b/src/AutoRest.CSharp/Common/Generation/Writers/RequestWriterHelpers.cs @@ -19,15 +19,14 @@ internal static class RequestWriterHelpers { private static string GetPipeline (bool lowLevel) => lowLevel ? "Pipeline" : "_pipeline"; - public static void WriteRequestCreation(CodeWriter writer, RestClientMethod clientMethod, bool lowLevel) + public static void WriteRequestCreation(CodeWriter writer, RestClientMethod clientMethod, bool lowLevel, string methodAccessibility) { using var methodScope = writer.AmbientScope(); var parameters = clientMethod.Parameters; var methodName = CreateRequestMethodName(clientMethod.Name); var returnType = lowLevel ? typeof(Azure.Core.Request) : typeof(HttpMessage); - var visibility = lowLevel ? "private" : (clientMethod.IsVisible ? "protected" : "internal"); - writer.Append($"{visibility} {returnType} {methodName}("); + writer.Append($"{methodAccessibility} {returnType} {methodName}("); foreach (Parameter clientParameter in parameters) { if (lowLevel) diff --git a/src/AutoRest.CSharp/Common/Generation/Writers/RestClientWriter.cs b/src/AutoRest.CSharp/Common/Generation/Writers/RestClientWriter.cs index 8abc55000bb..9bec9b9b658 100644 --- a/src/AutoRest.CSharp/Common/Generation/Writers/RestClientWriter.cs +++ b/src/AutoRest.CSharp/Common/Generation/Writers/RestClientWriter.cs @@ -98,7 +98,7 @@ private void WriteClientCtor(CodeWriter writer, RestClient restClient, CSharpTyp private void WriteRequestCreation(CodeWriter writer, RestClientMethod clientMethod) { - RequestWriterHelpers.WriteRequestCreation (writer, clientMethod, lowLevel: false); + RequestWriterHelpers.WriteRequestCreation (writer, clientMethod, lowLevel: false, "internal"); } private void WriteOperation(CodeWriter writer, RestClientMethod operation, bool async) diff --git a/src/AutoRest.CSharp/Common/Input/CodeModelPartials.cs b/src/AutoRest.CSharp/Common/Input/CodeModelPartials.cs index ab6f604e834..060b18c5cc2 100644 --- a/src/AutoRest.CSharp/Common/Input/CodeModelPartials.cs +++ b/src/AutoRest.CSharp/Common/Input/CodeModelPartials.cs @@ -23,6 +23,7 @@ internal partial class Operation // For some reason, booleans in dictionaries are deserialized as string instead of bool. public bool IsLongRunning => Convert.ToBoolean(Extensions.GetValue("x-ms-long-running-operation") ?? "false"); public string? LongRunningFinalStateVia => Extensions.GetValue>("x-ms-long-running-operation-options")?.GetValue("final-state-via"); + public string? Accessibility => Extensions.GetValue("x-accessibility"); public ServiceResponse LongRunningInitialResponse { diff --git a/src/AutoRest.CSharp/Common/Output/Models/ClientMethod.cs b/src/AutoRest.CSharp/Common/Output/Models/ClientMethod.cs index 70b389991d6..e97f23019ea 100644 --- a/src/AutoRest.CSharp/Common/Output/Models/ClientMethod.cs +++ b/src/AutoRest.CSharp/Common/Output/Models/ClientMethod.cs @@ -7,17 +7,19 @@ namespace AutoRest.CSharp.Output.Models { internal class ClientMethod { - public ClientMethod(string name, RestClientMethod restClientMethod, string? description, Diagnostic diagnostics) + public ClientMethod(string name, RestClientMethod restClientMethod, string? description, Diagnostic diagnostics, string accessibility) { Name = name; RestClientMethod = restClientMethod; Description = description; Diagnostics = diagnostics; + Accessibility = accessibility; } public string Name { get; } public RestClientMethod RestClientMethod { get; } public string? Description { get; } public Diagnostic Diagnostics { get; } + public string Accessibility { get; } } -} \ No newline at end of file +} diff --git a/src/AutoRest.CSharp/Common/Output/Models/Requests/PagingMethod.cs b/src/AutoRest.CSharp/Common/Output/Models/Requests/PagingMethod.cs index 153a4dc8ace..370e522bddb 100644 --- a/src/AutoRest.CSharp/Common/Output/Models/Requests/PagingMethod.cs +++ b/src/AutoRest.CSharp/Common/Output/Models/Requests/PagingMethod.cs @@ -20,5 +20,6 @@ public PagingMethod(RestClientMethod method, RestClientMethod? nextPageMethod, s public RestClientMethod? NextPageMethod { get; } public PagingResponseInfo PagingResponse { get; } public Diagnostic Diagnostics { get; } + public string Accessibility => "public"; } } diff --git a/src/AutoRest.CSharp/Common/Output/Models/Requests/RestClientMethod.cs b/src/AutoRest.CSharp/Common/Output/Models/Requests/RestClientMethod.cs index 4dffc75af6b..04a91925c5b 100644 --- a/src/AutoRest.CSharp/Common/Output/Models/Requests/RestClientMethod.cs +++ b/src/AutoRest.CSharp/Common/Output/Models/Requests/RestClientMethod.cs @@ -9,7 +9,7 @@ namespace AutoRest.CSharp.Output.Models.Requests { internal class RestClientMethod { - public RestClientMethod(string name, string? description, CSharpType? returnType, Request request, Parameter[] parameters, Response[] responses, DataPlaneResponseHeaderGroupType? headerModel, bool bufferResponse, bool isVisible) + public RestClientMethod(string name, string? description, CSharpType? returnType, Request request, Parameter[] parameters, Response[] responses, DataPlaneResponseHeaderGroupType? headerModel, bool bufferResponse, string accessibility) { Name = name; Request = request; @@ -19,7 +19,7 @@ public RestClientMethod(string name, string? description, CSharpType? returnType ReturnType = returnType; HeaderModel = headerModel; BufferResponse = bufferResponse; - IsVisible = isVisible; + Accessibility = accessibility; } public string Name { get; } @@ -30,6 +30,6 @@ public RestClientMethod(string name, string? description, CSharpType? returnType public DataPlaneResponseHeaderGroupType? HeaderModel { get; } public bool BufferResponse { get; } public CSharpType? ReturnType { get; } - public bool IsVisible { get; } + public string Accessibility { get; } } } diff --git a/src/AutoRest.CSharp/Common/Output/Models/RestClient.cs b/src/AutoRest.CSharp/Common/Output/Models/RestClient.cs index cb3cf17d84e..957d4f6268e 100644 --- a/src/AutoRest.CSharp/Common/Output/Models/RestClient.cs +++ b/src/AutoRest.CSharp/Common/Output/Models/RestClient.cs @@ -88,7 +88,7 @@ protected virtual Dictionary EnsureNormalMetho { continue; } - _requestMethods.Add(serviceRequest, Builder.BuildMethod(operation, httpRequest, serviceRequest.Parameters, null, false)); + _requestMethods.Add(serviceRequest, Builder.BuildMethod(operation, httpRequest, serviceRequest.Parameters, null, "public")); } } @@ -178,7 +178,7 @@ protected static RestClientMethod BuildNextPageMethod(RestClientMethod method, O responses, method.HeaderModel, bufferResponse: true, - isVisible: false); + accessibility: "internal"); } public virtual RestClientMethod? GetNextOperationMethod(ServiceRequest request) diff --git a/src/AutoRest.CSharp/Common/Output/Models/RestClientBuilder.cs b/src/AutoRest.CSharp/Common/Output/Models/RestClientBuilder.cs index bdaabd605f6..8a23f28ac39 100644 --- a/src/AutoRest.CSharp/Common/Output/Models/RestClientBuilder.cs +++ b/src/AutoRest.CSharp/Common/Output/Models/RestClientBuilder.cs @@ -61,7 +61,7 @@ private string GetRequestParameterName (RequestParameter requestParameter) return requestParameter.Language.Default.SerializedName ?? defaultName; } - public RestClientMethod BuildMethod(Operation operation, HttpRequest httpRequest, IEnumerable requestParameters, DataPlaneResponseHeaderGroupType? responseHeaderModel, bool isVisible) + public RestClientMethod BuildMethod(Operation operation, HttpRequest httpRequest, IEnumerable requestParameters, DataPlaneResponseHeaderGroupType? responseHeaderModel, string accessibility) { Dictionary allParameters = new (); @@ -89,7 +89,7 @@ public RestClientMethod BuildMethod(Operation operation, HttpRequest httpRequest responses, responseHeaderModel, operation.Extensions?.BufferResponse ?? true, - isVisible: isVisible + accessibility: accessibility ); } diff --git a/src/AutoRest.CSharp/DataPlane/Generation/DataPlaneClientWriter.cs b/src/AutoRest.CSharp/DataPlane/Generation/DataPlaneClientWriter.cs index 8ea621703b2..2a9ad978003 100644 --- a/src/AutoRest.CSharp/DataPlane/Generation/DataPlaneClientWriter.cs +++ b/src/AutoRest.CSharp/DataPlane/Generation/DataPlaneClientWriter.cs @@ -76,7 +76,7 @@ private void WriteClientMethod(CodeWriter writer, ClientMethod clientMethod, boo var methodName = CreateMethodName(clientMethod.Name, async); var asyncText = async ? "async" : string.Empty; - writer.Append($"public virtual {asyncText} {responseType} {methodName}("); + writer.Append($"{clientMethod.Accessibility} virtual {asyncText} {responseType} {methodName}("); foreach (Parameter parameter in parameters) { @@ -294,7 +294,7 @@ private void WritePagingOperation(CodeWriter writer, PagingMethod pagingMethod, writer.WriteXmlDocumentationParameter("cancellationToken", "The cancellation token to use."); writer.WriteXmlDocumentationRequiredParametersException(parameters); - writer.Append($"public virtual {responseType} {CreateMethodName(pagingMethod.Name, async)}("); + writer.Append($"{pagingMethod.Accessibility} virtual {responseType} {CreateMethodName(pagingMethod.Name, async)}("); foreach (Parameter parameter in parameters) { writer.WriteParameter(parameter); @@ -397,7 +397,7 @@ private void WriteStartOperationOperation(CodeWriter writer, DataPlaneLongRunnin writer.WriteXmlDocumentationRequiredParametersException(parameters); string asyncText = async ? "async " : string.Empty; - writer.Append($"public virtual {asyncText}{returnType} {CreateStartOperationName(lroMethod.Name, async)}("); + writer.Append($"{lroMethod.Accessibility} virtual {asyncText}{returnType} {CreateStartOperationName(lroMethod.Name, async)}("); foreach (Parameter parameter in parameters) { writer.WriteParameter(parameter); diff --git a/src/AutoRest.CSharp/DataPlane/Output/DataPlaneClient.cs b/src/AutoRest.CSharp/DataPlane/Output/DataPlaneClient.cs index bea512f8bb1..001a98c85d2 100644 --- a/src/AutoRest.CSharp/DataPlane/Output/DataPlaneClient.cs +++ b/src/AutoRest.CSharp/DataPlane/Output/DataPlaneClient.cs @@ -116,7 +116,8 @@ private IEnumerable BuildMethods() name, startMethod, BuilderHelpers.EscapeXmlDescription(operation.Language.Default.Description), - new Diagnostic($"{Declaration.Name}.{name}", Array.Empty())); + new Diagnostic($"{Declaration.Name}.{name}", Array.Empty()), + operation.Accessibility ?? "public"); } } } diff --git a/src/AutoRest.CSharp/DataPlane/Output/DataPlaneLongRunningOperationMethod.cs b/src/AutoRest.CSharp/DataPlane/Output/DataPlaneLongRunningOperationMethod.cs index 5a76f2d3a7f..8a7db051a3d 100644 --- a/src/AutoRest.CSharp/DataPlane/Output/DataPlaneLongRunningOperationMethod.cs +++ b/src/AutoRest.CSharp/DataPlane/Output/DataPlaneLongRunningOperationMethod.cs @@ -21,5 +21,6 @@ public DataPlaneLongRunningOperationMethod(string name, DataPlaneLongRunningOper public RestClientMethod StartMethod { get; } public Diagnostic Diagnostics { get; } + public string Accessibility => "public"; } } diff --git a/src/AutoRest.CSharp/DataPlane/Output/DataPlaneRestClient.cs b/src/AutoRest.CSharp/DataPlane/Output/DataPlaneRestClient.cs index 8a7c746a901..74e012749b3 100644 --- a/src/AutoRest.CSharp/DataPlane/Output/DataPlaneRestClient.cs +++ b/src/AutoRest.CSharp/DataPlane/Output/DataPlaneRestClient.cs @@ -46,7 +46,8 @@ protected override Dictionary EnsureNormalMeth continue; } var headerModel = _context.Library.FindHeaderModel(operation); - requestMethods.Add(serviceRequest, Builder.BuildMethod(operation, httpRequest, serviceRequest.Parameters, headerModel, false)); + var accessibility = operation.Accessibility ?? "public"; + requestMethods.Add(serviceRequest, Builder.BuildMethod(operation, httpRequest, serviceRequest.Parameters, headerModel, accessibility)); } } diff --git a/src/AutoRest.CSharp/LowLevel/Generation/LowLevelClientWriter.cs b/src/AutoRest.CSharp/LowLevel/Generation/LowLevelClientWriter.cs index 89e2689bea7..18062ef0d22 100644 --- a/src/AutoRest.CSharp/LowLevel/Generation/LowLevelClientWriter.cs +++ b/src/AutoRest.CSharp/LowLevel/Generation/LowLevelClientWriter.cs @@ -49,7 +49,7 @@ private void WriteClientMethodRequest(CodeWriter writer, RestClientMethod client { writer.WriteXmlDocumentationParameter(parameter.Name, parameter.Description); } - RequestWriterHelpers.WriteRequestCreation(writer, clientMethod, lowLevel: true); + RequestWriterHelpers.WriteRequestCreation(writer, clientMethod, lowLevel: true, "private"); } private void WriteClientMethod(CodeWriter writer, RestClientMethod clientMethod, bool async) @@ -68,7 +68,7 @@ private void WriteClientMethod(CodeWriter writer, RestClientMethod clientMethod, var methodName = CreateMethodName(clientMethod.Name, async); var asyncText = async ? "async" : string.Empty; - writer.Append($"public virtual {asyncText} {responseType} {methodName}("); + writer.Append($"{clientMethod.Accessibility} virtual {asyncText} {responseType} {methodName}("); foreach (var parameter in parameters) { diff --git a/src/AutoRest.CSharp/LowLevel/Output/LowLevelRestClient.cs b/src/AutoRest.CSharp/LowLevel/Output/LowLevelRestClient.cs index 73c892c6a95..4c3cc70bfa7 100644 --- a/src/AutoRest.CSharp/LowLevel/Output/LowLevelRestClient.cs +++ b/src/AutoRest.CSharp/LowLevel/Output/LowLevelRestClient.cs @@ -55,7 +55,8 @@ private IEnumerable BuildAllMethods() // will show up first. IEnumerable requestParameters = serviceRequest.Parameters.Where (FilterServiceParamaters); - RestClientMethod method = _builder.BuildMethod(operation, (HttpRequest)serviceRequest.Protocol.Http!, requestParameters, null, true); + var accessibility = operation.Accessibility ?? "public"; + RestClientMethod method = _builder.BuildMethod(operation, (HttpRequest)serviceRequest.Protocol.Http!, requestParameters, null, accessibility); List parameters = method.Parameters.ToList(); RequestBody? body = null; @@ -74,7 +75,7 @@ private IEnumerable BuildAllMethods() } Request request = new Request (method.Request.HttpMethod, method.Request.PathSegments, method.Request.Query, method.Request.Headers, body); - yield return new RestClientMethod (method.Name, method.Description, method.ReturnType, request, parameters.ToArray(), method.Responses, method.HeaderModel, method.BufferResponse, method.IsVisible); + yield return new RestClientMethod (method.Name, method.Description, method.ReturnType, request, parameters.ToArray(), method.Responses, method.HeaderModel, method.BufferResponse, method.Accessibility); } } } diff --git a/src/AutoRest.CSharp/Properties/launchSettings.json b/src/AutoRest.CSharp/Properties/launchSettings.json index 2d7795ab5c0..90e57c089e0 100644 --- a/src/AutoRest.CSharp/Properties/launchSettings.json +++ b/src/AutoRest.CSharp/Properties/launchSettings.json @@ -1,5 +1,13 @@ { "profiles": { + "Accessibility": { + "commandName": "Project", + "commandLineArgs": "--standalone $(SolutionDir)\\test\\TestProjects\\Accessibility\\Generated" + }, + "Accessibility-LowLevel": { + "commandName": "Project", + "commandLineArgs": "--standalone $(SolutionDir)\\test\\TestProjects\\Accessibility-LowLevel\\Generated" + }, "additionalProperties": { "commandName": "Project", "commandLineArgs": "--standalone $(SolutionDir)\\test\\TestServerProjects\\additionalProperties\\Generated" diff --git a/test/AutoRest.TestServer.Tests/AccessibilityTests.cs b/test/AutoRest.TestServer.Tests/AccessibilityTests.cs new file mode 100644 index 00000000000..b6074329510 --- /dev/null +++ b/test/AutoRest.TestServer.Tests/AccessibilityTests.cs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Linq; +using System.Reflection; +using Accessibility_LowLevel; +using NUnit.Framework; + +namespace AutoRest.TestServer.Tests +{ + public class AccessibilityTests + { + [Test] + public void AccessibilityHonoredOnOperations() + { + var client = typeof(AccessibilityClient); + Assert.AreEqual(true, client.GetMethod ("Operation").IsPublic, "Operation should be public"); + Assert.AreEqual(true, client.GetMethod ("OperationAsync").IsPublic, "OperationAsync should be public"); + Assert.AreEqual(true, client.GetMethod ("OperationInternal", BindingFlags.Instance | BindingFlags.NonPublic).IsAssembly, "OperationInternal should be internal"); + Assert.AreEqual(true, client.GetMethod ("OperationInternalAsync", BindingFlags.Instance | BindingFlags.NonPublic).IsAssembly, "OperationInternalAsync should be internal"); + } + } +} diff --git a/test/AutoRest.TestServerLowLevel.Tests/AccessibilityTests.cs b/test/AutoRest.TestServerLowLevel.Tests/AccessibilityTests.cs new file mode 100644 index 00000000000..b6074329510 --- /dev/null +++ b/test/AutoRest.TestServerLowLevel.Tests/AccessibilityTests.cs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Linq; +using System.Reflection; +using Accessibility_LowLevel; +using NUnit.Framework; + +namespace AutoRest.TestServer.Tests +{ + public class AccessibilityTests + { + [Test] + public void AccessibilityHonoredOnOperations() + { + var client = typeof(AccessibilityClient); + Assert.AreEqual(true, client.GetMethod ("Operation").IsPublic, "Operation should be public"); + Assert.AreEqual(true, client.GetMethod ("OperationAsync").IsPublic, "OperationAsync should be public"); + Assert.AreEqual(true, client.GetMethod ("OperationInternal", BindingFlags.Instance | BindingFlags.NonPublic).IsAssembly, "OperationInternal should be internal"); + Assert.AreEqual(true, client.GetMethod ("OperationInternalAsync", BindingFlags.Instance | BindingFlags.NonPublic).IsAssembly, "OperationInternalAsync should be internal"); + } + } +} diff --git a/test/AutoRest.TestServerLowLevel.Tests/AutoRest.TestServerLowLevel.Tests.csproj b/test/AutoRest.TestServerLowLevel.Tests/AutoRest.TestServerLowLevel.Tests.csproj index efde5151b40..d44f9fa192e 100644 --- a/test/AutoRest.TestServerLowLevel.Tests/AutoRest.TestServerLowLevel.Tests.csproj +++ b/test/AutoRest.TestServerLowLevel.Tests/AutoRest.TestServerLowLevel.Tests.csproj @@ -24,6 +24,7 @@ + diff --git a/test/TestProjects/Accessibility-LowLevel/Accessibility-LowLevel.json b/test/TestProjects/Accessibility-LowLevel/Accessibility-LowLevel.json new file mode 100644 index 00000000000..7a04219ef98 --- /dev/null +++ b/test/TestProjects/Accessibility-LowLevel/Accessibility-LowLevel.json @@ -0,0 +1,59 @@ +{ + "swagger": "2.0", + "info": { + "title": "Accessibility", + "description": "Accessibility", + "version": "1.0.0" + }, + "host": "localhost:3000", + "schemes": [ + "http" + ], + "produces": [ + "application/json" + ], + "consumes": [ + "application/json" + ], + "paths": { + "/Operation/": { + "put": { + "operationId": "Operation", + "parameters": [ + { + "name": "body", + "in": "body", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Received correct format" + } + } + } + }, + "/OperationInternal/": { + "put": { + "operationId": "OperationInternal", + "parameters": [ + { + "name": "body", + "in": "body", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Received correct format" + } + }, + "x-accessibility": "internal" + } + } + } +} diff --git a/test/TestProjects/Accessibility-LowLevel/Accessibility_LowLevel.csproj b/test/TestProjects/Accessibility-LowLevel/Accessibility_LowLevel.csproj new file mode 100644 index 00000000000..a6ad4abe177 --- /dev/null +++ b/test/TestProjects/Accessibility-LowLevel/Accessibility_LowLevel.csproj @@ -0,0 +1,13 @@ + + + + netstandard2.0 + true + annotations + + + + + + + diff --git a/test/TestProjects/Accessibility-LowLevel/Generated/AccessibilityClient.cs b/test/TestProjects/Accessibility-LowLevel/Generated/AccessibilityClient.cs new file mode 100644 index 00000000000..0694674722e --- /dev/null +++ b/test/TestProjects/Accessibility-LowLevel/Generated/AccessibilityClient.cs @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; + +#pragma warning disable AZC0007 + +namespace Accessibility_LowLevel +{ + /// The Accessibility service client. + public partial class AccessibilityClient + { + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline { get; } + private const string AuthorizationHeader = "Fake-Subscription-Key"; + private Uri endpoint; + private readonly string apiVersion; + + /// Initializes a new instance of AccessibilityClient for mocking. + protected AccessibilityClient() + { + } + + /// Initializes a new instance of AccessibilityClient. + /// A credential used to authenticate to an Azure Service. + /// server parameter. + /// The options for configuring the client. + public AccessibilityClient(AzureKeyCredential credential, Uri endpoint = null, AccessibilityClientOptions options = null) + { + if (credential == null) + { + throw new ArgumentNullException(nameof(credential)); + } + endpoint ??= new Uri("http://localhost:3000"); + + options ??= new AccessibilityClientOptions(); + Pipeline = HttpPipelineBuilder.Build(options, new AzureKeyCredentialPolicy(credential, AuthorizationHeader)); + this.endpoint = endpoint; + apiVersion = options.Version; + } + + /// The request body. + /// The cancellation token to use. + public virtual async Task OperationAsync(RequestContent requestBody, CancellationToken cancellationToken = default) + { + Request req = CreateOperationRequest(requestBody); + return await Pipeline.SendRequestAsync(req, cancellationToken).ConfigureAwait(false); + } + + /// The request body. + /// The cancellation token to use. + public virtual Response Operation(RequestContent requestBody, CancellationToken cancellationToken = default) + { + Request req = CreateOperationRequest(requestBody); + return Pipeline.SendRequest(req, cancellationToken); + } + + /// Create Request for and operations. + /// The request body. + private Request CreateOperationRequest(RequestContent requestBody) + { + var message = Pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendPath("/Operation/", false); + request.Uri = uri; + request.Headers.Add("Content-Type", "application/json"); + request.Content = requestBody; + return request; + } + + /// The request body. + /// The cancellation token to use. + internal virtual async Task OperationInternalAsync(RequestContent requestBody, CancellationToken cancellationToken = default) + { + Request req = CreateOperationInternalRequest(requestBody); + return await Pipeline.SendRequestAsync(req, cancellationToken).ConfigureAwait(false); + } + + /// The request body. + /// The cancellation token to use. + internal virtual Response OperationInternal(RequestContent requestBody, CancellationToken cancellationToken = default) + { + Request req = CreateOperationInternalRequest(requestBody); + return Pipeline.SendRequest(req, cancellationToken); + } + + /// Create Request for and operations. + /// The request body. + private Request CreateOperationInternalRequest(RequestContent requestBody) + { + var message = Pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendPath("/OperationInternal/", false); + request.Uri = uri; + request.Headers.Add("Content-Type", "application/json"); + request.Content = requestBody; + return request; + } + } +} diff --git a/test/TestProjects/Accessibility-LowLevel/Generated/AccessibilityClientOptions.cs b/test/TestProjects/Accessibility-LowLevel/Generated/AccessibilityClientOptions.cs new file mode 100644 index 00000000000..e555dd2ed14 --- /dev/null +++ b/test/TestProjects/Accessibility-LowLevel/Generated/AccessibilityClientOptions.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Accessibility_LowLevel +{ + /// Client options for AccessibilityClient. + public partial class AccessibilityClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V1_0_0; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "1.0.0". + V1_0_0 = 1, + } + + internal string Version { get; } + + /// Initializes new instance of AccessibilityClientOptions. + public AccessibilityClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V1_0_0 => "1.0.0", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/test/TestProjects/Accessibility-LowLevel/Generated/CodeModel.yaml b/test/TestProjects/Accessibility-LowLevel/Generated/CodeModel.yaml new file mode 100644 index 00000000000..cfead59ab83 --- /dev/null +++ b/test/TestProjects/Accessibility-LowLevel/Generated/CodeModel.yaml @@ -0,0 +1,198 @@ +!CodeModel +info: !Info + description: Accessibility + title: Accessibility +schemas: !Schemas + strings: + - !StringSchema &ref_0 + type: string + language: !Languages + default: + name: String + description: simple string + protocol: !Protocols {} + - !StringSchema &ref_3 + type: string + apiVersions: + - !ApiVersion + version: 1.0.0 + language: !Languages + default: + name: String + description: '' + protocol: !Protocols {} + constants: + - !ConstantSchema &ref_2 + type: constant + value: !ConstantValue + value: application/json + valueType: *ref_0 + language: !Languages + default: + name: ApplicationJson + description: Content Type 'application/json' + protocol: !Protocols {} +globalParameters: + - !Parameter &ref_1 + schema: *ref_0 + clientDefaultValue: http://localhost:3000 + implementation: Client + origin: modelerfour:synthesized/host + required: true + extensions: + x-ms-skip-url-encoding: true + language: !Languages + default: + name: $host + description: server parameter + serializedName: $host + protocol: !Protocols + http: !HttpParameter + in: uri +operationGroups: + - !OperationGroup + $key: '' + operations: + - !Operation + apiVersions: + - !ApiVersion + version: 1.0.0 + parameters: + - *ref_1 + requests: + - !Request + parameters: + - !Parameter + schema: *ref_2 + implementation: Method + origin: modelerfour:synthesized/content-type + required: true + language: !Languages + default: + name: contentType + description: Body Parameter content-type + serializedName: Content-Type + protocol: !Protocols + http: !HttpParameter + in: header + - !Parameter &ref_4 + schema: *ref_3 + implementation: Method + required: false + language: !Languages + default: + name: body + description: '' + protocol: !Protocols + http: !HttpParameter + in: body + style: json + signatureParameters: + - *ref_4 + language: !Languages + default: + name: '' + description: '' + protocol: !Protocols + http: !HttpWithBodyRequest + path: /Operation/ + method: put + knownMediaType: json + mediaTypes: + - application/json + uri: '{$host}' + signatureParameters: [] + responses: + - !Response + language: !Languages + default: + name: '' + description: Received correct format + protocol: !Protocols + http: !HttpResponse + statusCodes: + - '200' + language: !Languages + default: + name: Operation + description: '' + protocol: !Protocols {} + - !Operation + apiVersions: + - !ApiVersion + version: 1.0.0 + parameters: + - *ref_1 + requests: + - !Request + parameters: + - !Parameter + schema: *ref_2 + implementation: Method + origin: modelerfour:synthesized/content-type + required: true + language: !Languages + default: + name: contentType + description: Body Parameter content-type + serializedName: Content-Type + protocol: !Protocols + http: !HttpParameter + in: header + - !Parameter &ref_5 + schema: *ref_3 + implementation: Method + required: false + language: !Languages + default: + name: body + description: '' + protocol: !Protocols + http: !HttpParameter + in: body + style: json + signatureParameters: + - *ref_5 + language: !Languages + default: + name: '' + description: '' + protocol: !Protocols + http: !HttpWithBodyRequest + path: /OperationInternal/ + method: put + knownMediaType: json + mediaTypes: + - application/json + uri: '{$host}' + signatureParameters: [] + responses: + - !Response + language: !Languages + default: + name: '' + description: Received correct format + protocol: !Protocols + http: !HttpResponse + statusCodes: + - '200' + extensions: + x-accessibility: internal + language: !Languages + default: + name: OperationInternal + description: '' + protocol: !Protocols {} + language: !Languages + default: + name: '' + description: '' + protocol: !Protocols {} +security: !Security + authenticationRequired: false +language: !Languages + default: + name: Accessibility + description: '' +protocol: !Protocols + http: !HttpModel {} diff --git a/test/TestProjects/Accessibility-LowLevel/Generated/Configuration.json b/test/TestProjects/Accessibility-LowLevel/Generated/Configuration.json new file mode 100644 index 00000000000..1eb2426c9c1 --- /dev/null +++ b/test/TestProjects/Accessibility-LowLevel/Generated/Configuration.json @@ -0,0 +1,23 @@ +{ + "OutputFolder": ".", + "Namespace": "Accessibility_LowLevel", + "LibraryName": null, + "SharedSourceFolders": [ + "..\\..\\..\\..\\artifacts\\bin\\AutoRest.CSharp\\Debug\\netcoreapp3.1\\Generator.Shared", + "..\\..\\..\\..\\artifacts\\bin\\AutoRest.CSharp\\Debug\\netcoreapp3.1\\Azure.Core.Shared" + ], + "AzureArm": false, + "PublicClients": true, + "ModelNamespace": true, + "HeadAsBoolean": false, + "SkipCSProjPackageReference": true, + "LowLevelClient": true, + "CredentialTypes": [ + "AzureKeyCredential" + ], + "CredentialScopes": [], + "CredentialHeaderName": "Fake-Subscription-Key", + "OperationGroupToResourceType": {}, + "OperationGroupToResource": {}, + "OperationGroupToParent": {} +} \ No newline at end of file diff --git a/test/TestProjects/Accessibility-LowLevel/readme.md b/test/TestProjects/Accessibility-LowLevel/readme.md new file mode 100644 index 00000000000..f0b80427a9f --- /dev/null +++ b/test/TestProjects/Accessibility-LowLevel/readme.md @@ -0,0 +1,13 @@ +# Accessibility + +### AutoRest Configuration + +> see https://aka.ms/autorest + +```yaml +require: $(this-folder)/../../../readme.md +input-file: $(this-folder)\Accessibility-LowLevel.json +low-level-client: true +credential-types: AzureKeyCredential +credential-header-name: Fake-Subscription-Key +``` \ No newline at end of file diff --git a/test/TestProjects/Accessibility/Accessibility.csproj b/test/TestProjects/Accessibility/Accessibility.csproj new file mode 100644 index 00000000000..a6ad4abe177 --- /dev/null +++ b/test/TestProjects/Accessibility/Accessibility.csproj @@ -0,0 +1,13 @@ + + + + netstandard2.0 + true + annotations + + + + + + + diff --git a/test/TestProjects/Accessibility/Accessibility.json b/test/TestProjects/Accessibility/Accessibility.json new file mode 100644 index 00000000000..7a04219ef98 --- /dev/null +++ b/test/TestProjects/Accessibility/Accessibility.json @@ -0,0 +1,59 @@ +{ + "swagger": "2.0", + "info": { + "title": "Accessibility", + "description": "Accessibility", + "version": "1.0.0" + }, + "host": "localhost:3000", + "schemes": [ + "http" + ], + "produces": [ + "application/json" + ], + "consumes": [ + "application/json" + ], + "paths": { + "/Operation/": { + "put": { + "operationId": "Operation", + "parameters": [ + { + "name": "body", + "in": "body", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Received correct format" + } + } + } + }, + "/OperationInternal/": { + "put": { + "operationId": "OperationInternal", + "parameters": [ + { + "name": "body", + "in": "body", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Received correct format" + } + }, + "x-accessibility": "internal" + } + } + } +} diff --git a/test/TestProjects/Accessibility/Generated/AccessibilityClient.cs b/test/TestProjects/Accessibility/Generated/AccessibilityClient.cs new file mode 100644 index 00000000000..38fe6a4c354 --- /dev/null +++ b/test/TestProjects/Accessibility/Generated/AccessibilityClient.cs @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Azure; +using Azure.Core.Pipeline; + +namespace Accessibility +{ + /// The Accessibility service client. + public partial class AccessibilityClient + { + private readonly ClientDiagnostics _clientDiagnostics; + private readonly HttpPipeline _pipeline; + internal AccessibilityRestClient RestClient { get; } + + /// Initializes a new instance of AccessibilityClient for mocking. + protected AccessibilityClient() + { + } + + /// Initializes a new instance of AccessibilityClient. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// server parameter. + internal AccessibilityClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Uri endpoint = null) + { + RestClient = new AccessibilityRestClient(clientDiagnostics, pipeline, endpoint); + _clientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + } + + /// The String to use. + /// The cancellation token to use. + public virtual async Task OperationAsync(string body = null, CancellationToken cancellationToken = default) + { + using var scope = _clientDiagnostics.CreateScope("AccessibilityClient.Operation"); + scope.Start(); + try + { + return await RestClient.OperationAsync(body, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// The String to use. + /// The cancellation token to use. + public virtual Response Operation(string body = null, CancellationToken cancellationToken = default) + { + using var scope = _clientDiagnostics.CreateScope("AccessibilityClient.Operation"); + scope.Start(); + try + { + return RestClient.Operation(body, cancellationToken); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// The String to use. + /// The cancellation token to use. + internal virtual async Task OperationInternalAsync(string body = null, CancellationToken cancellationToken = default) + { + using var scope = _clientDiagnostics.CreateScope("AccessibilityClient.OperationInternal"); + scope.Start(); + try + { + return await RestClient.OperationInternalAsync(body, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// The String to use. + /// The cancellation token to use. + internal virtual Response OperationInternal(string body = null, CancellationToken cancellationToken = default) + { + using var scope = _clientDiagnostics.CreateScope("AccessibilityClient.OperationInternal"); + scope.Start(); + try + { + return RestClient.OperationInternal(body, cancellationToken); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + } +} diff --git a/test/TestProjects/Accessibility/Generated/AccessibilityClientOptions.cs b/test/TestProjects/Accessibility/Generated/AccessibilityClientOptions.cs new file mode 100644 index 00000000000..67720495f76 --- /dev/null +++ b/test/TestProjects/Accessibility/Generated/AccessibilityClientOptions.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Accessibility +{ + /// Client options for AccessibilityClient. + public partial class AccessibilityClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V1_0_0; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "1.0.0". + V1_0_0 = 1, + } + + internal string Version { get; } + + /// Initializes new instance of AccessibilityClientOptions. + public AccessibilityClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V1_0_0 => "1.0.0", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/test/TestProjects/Accessibility/Generated/AccessibilityRestClient.cs b/test/TestProjects/Accessibility/Generated/AccessibilityRestClient.cs new file mode 100644 index 00000000000..28ad14a0aca --- /dev/null +++ b/test/TestProjects/Accessibility/Generated/AccessibilityRestClient.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Accessibility +{ + internal partial class AccessibilityRestClient + { + private Uri endpoint; + private ClientDiagnostics _clientDiagnostics; + private HttpPipeline _pipeline; + + /// Initializes a new instance of AccessibilityRestClient. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// server parameter. + public AccessibilityRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Uri endpoint = null) + { + endpoint ??= new Uri("http://localhost:3000"); + + this.endpoint = endpoint; + _clientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + } + + internal HttpMessage CreateOperationRequest(string body) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendPath("/Operation/", false); + request.Uri = uri; + if (body != null) + { + request.Headers.Add("Content-Type", "application/json"); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteStringValue(body); + request.Content = content; + } + return message; + } + + /// The String to use. + /// The cancellation token to use. + public async Task OperationAsync(string body = null, CancellationToken cancellationToken = default) + { + using var message = CreateOperationRequest(body); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + return message.Response; + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// The String to use. + /// The cancellation token to use. + public Response Operation(string body = null, CancellationToken cancellationToken = default) + { + using var message = CreateOperationRequest(body); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + return message.Response; + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + + internal HttpMessage CreateOperationInternalRequest(string body) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(endpoint); + uri.AppendPath("/OperationInternal/", false); + request.Uri = uri; + if (body != null) + { + request.Headers.Add("Content-Type", "application/json"); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteStringValue(body); + request.Content = content; + } + return message; + } + + /// The String to use. + /// The cancellation token to use. + public async Task OperationInternalAsync(string body = null, CancellationToken cancellationToken = default) + { + using var message = CreateOperationInternalRequest(body); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + return message.Response; + default: + throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); + } + } + + /// The String to use. + /// The cancellation token to use. + public Response OperationInternal(string body = null, CancellationToken cancellationToken = default) + { + using var message = CreateOperationInternalRequest(body); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + return message.Response; + default: + throw _clientDiagnostics.CreateRequestFailedException(message.Response); + } + } + } +} diff --git a/test/TestProjects/Accessibility/Generated/CodeModel.yaml b/test/TestProjects/Accessibility/Generated/CodeModel.yaml new file mode 100644 index 00000000000..cfead59ab83 --- /dev/null +++ b/test/TestProjects/Accessibility/Generated/CodeModel.yaml @@ -0,0 +1,198 @@ +!CodeModel +info: !Info + description: Accessibility + title: Accessibility +schemas: !Schemas + strings: + - !StringSchema &ref_0 + type: string + language: !Languages + default: + name: String + description: simple string + protocol: !Protocols {} + - !StringSchema &ref_3 + type: string + apiVersions: + - !ApiVersion + version: 1.0.0 + language: !Languages + default: + name: String + description: '' + protocol: !Protocols {} + constants: + - !ConstantSchema &ref_2 + type: constant + value: !ConstantValue + value: application/json + valueType: *ref_0 + language: !Languages + default: + name: ApplicationJson + description: Content Type 'application/json' + protocol: !Protocols {} +globalParameters: + - !Parameter &ref_1 + schema: *ref_0 + clientDefaultValue: http://localhost:3000 + implementation: Client + origin: modelerfour:synthesized/host + required: true + extensions: + x-ms-skip-url-encoding: true + language: !Languages + default: + name: $host + description: server parameter + serializedName: $host + protocol: !Protocols + http: !HttpParameter + in: uri +operationGroups: + - !OperationGroup + $key: '' + operations: + - !Operation + apiVersions: + - !ApiVersion + version: 1.0.0 + parameters: + - *ref_1 + requests: + - !Request + parameters: + - !Parameter + schema: *ref_2 + implementation: Method + origin: modelerfour:synthesized/content-type + required: true + language: !Languages + default: + name: contentType + description: Body Parameter content-type + serializedName: Content-Type + protocol: !Protocols + http: !HttpParameter + in: header + - !Parameter &ref_4 + schema: *ref_3 + implementation: Method + required: false + language: !Languages + default: + name: body + description: '' + protocol: !Protocols + http: !HttpParameter + in: body + style: json + signatureParameters: + - *ref_4 + language: !Languages + default: + name: '' + description: '' + protocol: !Protocols + http: !HttpWithBodyRequest + path: /Operation/ + method: put + knownMediaType: json + mediaTypes: + - application/json + uri: '{$host}' + signatureParameters: [] + responses: + - !Response + language: !Languages + default: + name: '' + description: Received correct format + protocol: !Protocols + http: !HttpResponse + statusCodes: + - '200' + language: !Languages + default: + name: Operation + description: '' + protocol: !Protocols {} + - !Operation + apiVersions: + - !ApiVersion + version: 1.0.0 + parameters: + - *ref_1 + requests: + - !Request + parameters: + - !Parameter + schema: *ref_2 + implementation: Method + origin: modelerfour:synthesized/content-type + required: true + language: !Languages + default: + name: contentType + description: Body Parameter content-type + serializedName: Content-Type + protocol: !Protocols + http: !HttpParameter + in: header + - !Parameter &ref_5 + schema: *ref_3 + implementation: Method + required: false + language: !Languages + default: + name: body + description: '' + protocol: !Protocols + http: !HttpParameter + in: body + style: json + signatureParameters: + - *ref_5 + language: !Languages + default: + name: '' + description: '' + protocol: !Protocols + http: !HttpWithBodyRequest + path: /OperationInternal/ + method: put + knownMediaType: json + mediaTypes: + - application/json + uri: '{$host}' + signatureParameters: [] + responses: + - !Response + language: !Languages + default: + name: '' + description: Received correct format + protocol: !Protocols + http: !HttpResponse + statusCodes: + - '200' + extensions: + x-accessibility: internal + language: !Languages + default: + name: OperationInternal + description: '' + protocol: !Protocols {} + language: !Languages + default: + name: '' + description: '' + protocol: !Protocols {} +security: !Security + authenticationRequired: false +language: !Languages + default: + name: Accessibility + description: '' +protocol: !Protocols + http: !HttpModel {} diff --git a/test/TestProjects/Accessibility/Generated/Configuration.json b/test/TestProjects/Accessibility/Generated/Configuration.json new file mode 100644 index 00000000000..b9c650881b5 --- /dev/null +++ b/test/TestProjects/Accessibility/Generated/Configuration.json @@ -0,0 +1,21 @@ +{ + "OutputFolder": ".", + "Namespace": "Accessibility", + "LibraryName": null, + "SharedSourceFolders": [ + "..\\..\\..\\..\\artifacts\\bin\\AutoRest.CSharp\\Debug\\netcoreapp3.1\\Generator.Shared", + "..\\..\\..\\..\\artifacts\\bin\\AutoRest.CSharp\\Debug\\netcoreapp3.1\\Azure.Core.Shared" + ], + "AzureArm": false, + "PublicClients": true, + "ModelNamespace": true, + "HeadAsBoolean": false, + "SkipCSProjPackageReference": true, + "LowLevelClient": false, + "CredentialTypes": [], + "CredentialScopes": [], + "CredentialHeaderName": "api-key", + "OperationGroupToResourceType": {}, + "OperationGroupToResource": {}, + "OperationGroupToParent": {} +} \ No newline at end of file