diff --git a/src/Grpc.AspNetCore.Web/GrpcWebApplicationBuilderExtensions.cs b/src/Grpc.AspNetCore.Web/GrpcWebApplicationBuilderExtensions.cs index d5b8a2806..17c301b62 100644 --- a/src/Grpc.AspNetCore.Web/GrpcWebApplicationBuilderExtensions.cs +++ b/src/Grpc.AspNetCore.Web/GrpcWebApplicationBuilderExtensions.cs @@ -32,10 +32,7 @@ public static class GrpcWebApplicationBuilderExtensions /// /// The to add the middleware to. /// A reference to this instance after the operation has completed. - public static IApplicationBuilder UseGrpcWeb(this IApplicationBuilder builder) - { - return builder.UseGrpcWeb(new GrpcWebOptions()); - } + public static IApplicationBuilder UseGrpcWeb(this IApplicationBuilder builder) => builder.UseGrpcWeb(new GrpcWebOptions()); /// /// Adds gRPC-Web middleware to the specified . diff --git a/src/Grpc.Auth/GoogleAuthInterceptors.cs b/src/Grpc.Auth/GoogleAuthInterceptors.cs index d5b90db81..c4779c878 100644 --- a/src/Grpc.Auth/GoogleAuthInterceptors.cs +++ b/src/Grpc.Auth/GoogleAuthInterceptors.cs @@ -58,8 +58,7 @@ public static AsyncAuthInterceptor FromCredential(ITokenAccess credential) /// The credential to use to obtain access tokens. /// The interceptor. public static AsyncAuthInterceptor FromCredential(ITokenAccessWithHeaders credential) - { - return new AsyncAuthInterceptor(async (context, metadata) => + => new AsyncAuthInterceptor(async (context, metadata) => { AccessTokenWithHeaders tokenAndHeaders = await credential.GetAccessTokenWithHeadersForRequestAsync(context.ServiceUrl, CancellationToken.None).ConfigureAwait(false); metadata.Add(CreateBearerTokenHeader(tokenAndHeaders.AccessToken)); @@ -71,7 +70,6 @@ public static AsyncAuthInterceptor FromCredential(ITokenAccessWithHeaders creden } } }); - } /// /// Creates an that will use given access token as authorization. @@ -89,15 +87,10 @@ public static AsyncAuthInterceptor FromAccessToken(string accessToken) } private static Metadata.Entry CreateBearerTokenHeader(string accessToken) - { - return new Metadata.Entry(AuthorizationHeader, Schema + " " + accessToken); - } + => new Metadata.Entry(AuthorizationHeader, Schema + " " + accessToken); /// /// Framework independent equivalent of Task.CompletedTask. /// - private static Task GetCompletedTask() - { - return Task.CompletedTask; - } + private static Task GetCompletedTask() => Task.CompletedTask; } diff --git a/src/Grpc.Auth/GoogleGrpcCredentials.cs b/src/Grpc.Auth/GoogleGrpcCredentials.cs index 1545e03fb..18e4816cd 100644 --- a/src/Grpc.Auth/GoogleGrpcCredentials.cs +++ b/src/Grpc.Auth/GoogleGrpcCredentials.cs @@ -51,9 +51,7 @@ public static async Task GetApplicationDefaultAsync() /// OAuth2 access token. /// The CallCredentials instance. public static CallCredentials FromAccessToken(string accessToken) - { - return CallCredentials.FromInterceptor(GoogleAuthInterceptors.FromAccessToken(accessToken)); - } + => CallCredentials.FromInterceptor(GoogleAuthInterceptors.FromAccessToken(accessToken)); /// /// Converts a ITokenAccess (e.g. GoogleCredential) object @@ -62,9 +60,7 @@ public static CallCredentials FromAccessToken(string accessToken) /// The credential to use to obtain access tokens. /// The CallCredentials instance. public static CallCredentials ToCallCredentials(this ITokenAccess credential) - { - return CallCredentials.FromInterceptor(GoogleAuthInterceptors.FromCredential(credential)); - } + => CallCredentials.FromInterceptor(GoogleAuthInterceptors.FromCredential(credential)); /// /// Converts a ITokenAccess (e.g. GoogleCredential) object @@ -74,7 +70,5 @@ public static CallCredentials ToCallCredentials(this ITokenAccess credential) /// The credential to use to obtain access tokens. /// >The ChannelCredentials instance. public static ChannelCredentials ToChannelCredentials(this ITokenAccess googleCredential) - { - return ChannelCredentials.Create(new SslCredentials(), googleCredential.ToCallCredentials()); - } + => ChannelCredentials.Create(new SslCredentials(), googleCredential.ToCallCredentials()); } diff --git a/src/Grpc.Core.Api/AsyncAuthInterceptor.cs b/src/Grpc.Core.Api/AsyncAuthInterceptor.cs index b63312cd8..80746e021 100644 --- a/src/Grpc.Core.Api/AsyncAuthInterceptor.cs +++ b/src/Grpc.Core.Api/AsyncAuthInterceptor.cs @@ -59,24 +59,15 @@ public AuthInterceptorContext(string serviceUrl, string methodName, Cancellation /// /// The fully qualified service URL for the RPC being called. /// - public string ServiceUrl - { - get { return serviceUrl; } - } + public string ServiceUrl => serviceUrl; /// /// The method name of the RPC being called. /// - public string MethodName - { - get { return methodName; } - } + public string MethodName => methodName; /// /// The cancellation token of the RPC being called. /// - public CancellationToken CancellationToken - { - get { return cancellationToken; } - } + public CancellationToken CancellationToken => cancellationToken; } diff --git a/src/Grpc.Core.Api/AsyncClientStreamingCall.cs b/src/Grpc.Core.Api/AsyncClientStreamingCall.cs index 789ed9c3d..c2fdfbeef 100644 --- a/src/Grpc.Core.Api/AsyncClientStreamingCall.cs +++ b/src/Grpc.Core.Api/AsyncClientStreamingCall.cs @@ -84,45 +84,24 @@ public AsyncClientStreamingCall(IClientStreamWriter requestStream, /// /// Asynchronous call result. /// - public Task ResponseAsync - { - get - { - return this.responseAsync; - } - } + public Task ResponseAsync => this.responseAsync; /// /// Asynchronous access to response headers. /// - public Task ResponseHeadersAsync - { - get - { - return callState.ResponseHeadersAsync(); - } - } + public Task ResponseHeadersAsync => callState.ResponseHeadersAsync(); /// /// Async stream to send streaming requests. /// - public IClientStreamWriter RequestStream - { - get - { - return requestStream; - } - } + public IClientStreamWriter RequestStream => requestStream; /// /// Gets an awaiter used to await this . /// /// An awaiter instance. /// This method is intended for compiler use rather than use directly in code. - public TaskAwaiter GetAwaiter() - { - return responseAsync.GetAwaiter(); - } + public TaskAwaiter GetAwaiter() => responseAsync.GetAwaiter(); /// /// Configures an awaiter used to await this . @@ -132,27 +111,19 @@ public TaskAwaiter GetAwaiter() /// /// An object used to await this task. public ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) - { - return responseAsync.ConfigureAwait(continueOnCapturedContext); - } + => responseAsync.ConfigureAwait(continueOnCapturedContext); /// /// Gets the call status if the call has already finished. /// Throws InvalidOperationException otherwise. /// - public Status GetStatus() - { - return callState.GetStatus(); - } + public Status GetStatus() => callState.GetStatus(); /// /// Gets the call trailing metadata if the call has already finished. /// Throws InvalidOperationException otherwise. /// - public Metadata GetTrailers() - { - return callState.GetTrailers(); - } + public Metadata GetTrailers() => callState.GetTrailers(); /// /// Provides means to cleanup after the call. @@ -164,21 +135,13 @@ public Metadata GetTrailers() /// Normally, there is no need for you to dispose the call unless you want to utilize the /// "Cancel" semantics of invoking Dispose. /// - public void Dispose() - { - callState.Dispose(); - } + public void Dispose() => callState.Dispose(); private string DebuggerToString() => CallDebuggerHelpers.DebuggerToString(callState); - private sealed class AsyncClientStreamingCallDebugView + private sealed class AsyncClientStreamingCallDebugView(AsyncClientStreamingCall call) { - private readonly AsyncClientStreamingCall _call; - - public AsyncClientStreamingCallDebugView(AsyncClientStreamingCall call) - { - _call = call; - } + private readonly AsyncClientStreamingCall _call = call; public bool IsComplete => CallDebuggerHelpers.GetStatus(_call.callState) != null; public Status? Status => CallDebuggerHelpers.GetStatus(_call.callState); diff --git a/src/Grpc.Core.Api/AsyncDuplexStreamingCall.cs b/src/Grpc.Core.Api/AsyncDuplexStreamingCall.cs index a9b275d3e..eae901f5d 100644 --- a/src/Grpc.Core.Api/AsyncDuplexStreamingCall.cs +++ b/src/Grpc.Core.Api/AsyncDuplexStreamingCall.cs @@ -83,53 +83,29 @@ public AsyncDuplexStreamingCall(IClientStreamWriter requestStream, /// /// Async stream to read streaming responses. /// - public IAsyncStreamReader ResponseStream - { - get - { - return responseStream; - } - } + public IAsyncStreamReader ResponseStream => responseStream; /// /// Async stream to send streaming requests. /// - public IClientStreamWriter RequestStream - { - get - { - return requestStream; - } - } + public IClientStreamWriter RequestStream => requestStream; /// /// Asynchronous access to response headers. /// - public Task ResponseHeadersAsync - { - get - { - return callState.ResponseHeadersAsync(); - } - } + public Task ResponseHeadersAsync => callState.ResponseHeadersAsync(); /// /// Gets the call status if the call has already finished. /// Throws InvalidOperationException otherwise. /// - public Status GetStatus() - { - return callState.GetStatus(); - } + public Status GetStatus() => callState.GetStatus(); /// /// Gets the call trailing metadata if the call has already finished. /// Throws InvalidOperationException otherwise. /// - public Metadata GetTrailers() - { - return callState.GetTrailers(); - } + public Metadata GetTrailers() => callState.GetTrailers(); /// /// Provides means to cleanup after the call. @@ -141,21 +117,13 @@ public Metadata GetTrailers() /// Normally, there is no need for you to dispose the call unless you want to utilize the /// "Cancel" semantics of invoking Dispose. /// - public void Dispose() - { - callState.Dispose(); - } + public void Dispose() => callState.Dispose(); private string DebuggerToString() => CallDebuggerHelpers.DebuggerToString(callState); - private sealed class AsyncDuplexStreamingCallDebugView + private sealed class AsyncDuplexStreamingCallDebugView(AsyncDuplexStreamingCall call) { - private readonly AsyncDuplexStreamingCall _call; - - public AsyncDuplexStreamingCallDebugView(AsyncDuplexStreamingCall call) - { - _call = call; - } + private readonly AsyncDuplexStreamingCall _call = call; public bool IsComplete => CallDebuggerHelpers.GetStatus(_call.callState) != null; public Status? Status => CallDebuggerHelpers.GetStatus(_call.callState); diff --git a/src/Grpc.Core.Api/AsyncServerStreamingCall.cs b/src/Grpc.Core.Api/AsyncServerStreamingCall.cs index efdf2b887..14c13a1fb 100644 --- a/src/Grpc.Core.Api/AsyncServerStreamingCall.cs +++ b/src/Grpc.Core.Api/AsyncServerStreamingCall.cs @@ -75,42 +75,24 @@ public AsyncServerStreamingCall(IAsyncStreamReader responseStream, /// /// Async stream to read streaming responses. /// - public IAsyncStreamReader ResponseStream - { - get - { - return responseStream; - } - } + public IAsyncStreamReader ResponseStream => responseStream; /// /// Asynchronous access to response headers. /// - public Task ResponseHeadersAsync - { - get - { - return callState.ResponseHeadersAsync(); - } - } + public Task ResponseHeadersAsync => callState.ResponseHeadersAsync(); /// /// Gets the call status if the call has already finished. /// Throws InvalidOperationException otherwise. /// - public Status GetStatus() - { - return callState.GetStatus(); - } + public Status GetStatus() => callState.GetStatus(); /// /// Gets the call trailing metadata if the call has already finished. /// Throws InvalidOperationException otherwise. /// - public Metadata GetTrailers() - { - return callState.GetTrailers(); - } + public Metadata GetTrailers() => callState.GetTrailers(); /// /// Provides means to cleanup after the call. @@ -122,21 +104,13 @@ public Metadata GetTrailers() /// Normally, there is no need for you to dispose the call unless you want to utilize the /// "Cancel" semantics of invoking Dispose. /// - public void Dispose() - { - callState.Dispose(); - } + public void Dispose() => callState.Dispose(); private string DebuggerToString() => CallDebuggerHelpers.DebuggerToString(callState); - private sealed class AsyncServerStreamingCallDebugView + private sealed class AsyncServerStreamingCallDebugView(AsyncServerStreamingCall call) { - private readonly AsyncServerStreamingCall _call; - - public AsyncServerStreamingCallDebugView(AsyncServerStreamingCall call) - { - _call = call; - } + private readonly AsyncServerStreamingCall _call = call; public bool IsComplete => CallDebuggerHelpers.GetStatus(_call.callState) != null; public Status? Status => CallDebuggerHelpers.GetStatus(_call.callState); diff --git a/src/Grpc.Core.Api/AsyncUnaryCall.cs b/src/Grpc.Core.Api/AsyncUnaryCall.cs index e3292b33a..583e93cba 100644 --- a/src/Grpc.Core.Api/AsyncUnaryCall.cs +++ b/src/Grpc.Core.Api/AsyncUnaryCall.cs @@ -76,34 +76,19 @@ public AsyncUnaryCall(Task responseAsync, /// /// Asynchronous call result. /// - public Task ResponseAsync - { - get - { - return this.responseAsync; - } - } + public Task ResponseAsync => this.responseAsync; /// /// Asynchronous access to response headers. /// - public Task ResponseHeadersAsync - { - get - { - return callState.ResponseHeadersAsync(); - } - } + public Task ResponseHeadersAsync => callState.ResponseHeadersAsync(); /// /// Gets an awaiter used to await this . /// /// An awaiter instance. /// This method is intended for compiler use rather than use directly in code. - public TaskAwaiter GetAwaiter() - { - return responseAsync.GetAwaiter(); - } + public TaskAwaiter GetAwaiter() => responseAsync.GetAwaiter(); /// /// Configures an awaiter used to await this . @@ -113,27 +98,19 @@ public TaskAwaiter GetAwaiter() /// /// An object used to await this task. public ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) - { - return responseAsync.ConfigureAwait(continueOnCapturedContext); - } + => responseAsync.ConfigureAwait(continueOnCapturedContext); /// /// Gets the call status if the call has already finished. /// Throws InvalidOperationException otherwise. /// - public Status GetStatus() - { - return callState.GetStatus(); - } + public Status GetStatus() => callState.GetStatus(); /// /// Gets the call trailing metadata if the call has already finished. /// Throws InvalidOperationException otherwise. /// - public Metadata GetTrailers() - { - return callState.GetTrailers(); - } + public Metadata GetTrailers() => callState.GetTrailers(); /// /// Provides means to cleanup after the call. @@ -145,21 +122,13 @@ public Metadata GetTrailers() /// Normally, there is no need for you to dispose the call unless you want to utilize the /// "Cancel" semantics of invoking Dispose. /// - public void Dispose() - { - callState.Dispose(); - } + public void Dispose() => callState.Dispose(); private string DebuggerToString() => CallDebuggerHelpers.DebuggerToString(callState); - private sealed class AsyncUnaryCallDebugView + private sealed class AsyncUnaryCallDebugView(AsyncUnaryCall call) { - private readonly AsyncUnaryCall _call; - - public AsyncUnaryCallDebugView(AsyncUnaryCall call) - { - _call = call; - } + private readonly AsyncUnaryCall _call = call; public bool IsComplete => CallDebuggerHelpers.GetStatus(_call.callState) != null; public Status? Status => CallDebuggerHelpers.GetStatus(_call.callState); diff --git a/src/Grpc.Core.Api/AuthContext.cs b/src/Grpc.Core.Api/AuthContext.cs index f296bfafb..0ee789866 100644 --- a/src/Grpc.Core.Api/AuthContext.cs +++ b/src/Grpc.Core.Api/AuthContext.cs @@ -49,25 +49,13 @@ public AuthContext(string? peerIdentityPropertyName, Dictionary /// Returns true if the peer is authenticated. /// - public bool IsPeerAuthenticated - { - get - { - return peerIdentityPropertyName != null; - } - } + public bool IsPeerAuthenticated => peerIdentityPropertyName != null; /// /// Gets the name of the property that indicates the peer identity. Returns null /// if the peer is not authenticated. /// - public string? PeerIdentityPropertyName - { - get - { - return peerIdentityPropertyName; - } - } + public string? PeerIdentityPropertyName => peerIdentityPropertyName; /// /// Gets properties that represent the peer identity (there can be more than one). Returns an empty collection @@ -88,13 +76,7 @@ public IEnumerable PeerIdentity /// /// Gets the auth properties of this context. /// - public IEnumerable Properties - { - get - { - return properties.Values.SelectMany(v => v); - } - } + public IEnumerable Properties => properties.Values.SelectMany(v => v); /// /// Returns the auth properties with given name (there can be more than one). diff --git a/src/Grpc.Core.Api/AuthProperty.cs b/src/Grpc.Core.Api/AuthProperty.cs index bde4c03d2..6ad7aad65 100644 --- a/src/Grpc.Core.Api/AuthProperty.cs +++ b/src/Grpc.Core.Api/AuthProperty.cs @@ -43,24 +43,12 @@ private AuthProperty(string name, byte[] valueBytes) /// /// Gets the name of the property. /// - public string Name - { - get - { - return name; - } - } + public string Name => name; /// /// Gets the string value of the property. /// - public string Value - { - get - { - return lazyValue ??= EncodingUTF8.GetString(this.valueBytes); - } - } + public string Value => lazyValue ??= EncodingUTF8.GetString(this.valueBytes); /// /// Gets the binary value of the property. @@ -91,19 +79,10 @@ public static AuthProperty Create(string name, byte[] valueBytes) /// /// Gets the binary value of the property (without making a defensive copy). /// - internal byte[] ValueBytesUnsafe - { - get - { - return valueBytes; - } - } + internal byte[] ValueBytesUnsafe => valueBytes; /// /// Creates and instance of AuthProperty without making a defensive copy of valueBytes. /// - internal static AuthProperty CreateUnsafe(string name, byte[] valueBytes) - { - return new AuthProperty(name, valueBytes); - } + internal static AuthProperty CreateUnsafe(string name, byte[] valueBytes) => new AuthProperty(name, valueBytes); } diff --git a/src/Grpc.Core.Api/BindServiceMethodAttribute.cs b/src/Grpc.Core.Api/BindServiceMethodAttribute.cs index f911994ee..6b9326b6d 100644 --- a/src/Grpc.Core.Api/BindServiceMethodAttribute.cs +++ b/src/Grpc.Core.Api/BindServiceMethodAttribute.cs @@ -27,33 +27,28 @@ namespace Grpc.Core; /// The bind method signature takes a and an optional /// instance of the service base class, e.g. static void BindService(ServiceBinderBase, GreeterService). /// +/// +/// Initializes a new instance of the class. +/// +/// The type the service bind method is defined on. +/// The name of the service bind method. [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] -public class BindServiceMethodAttribute : Attribute +public class BindServiceMethodAttribute([DynamicallyAccessedMembers(BindServiceMethodAttribute.ServiceBinderAccessibility)] Type bindType, + string bindMethodName) : Attribute { // Grpc.AspNetCore.Server uses reflection to find the bind service method. // Grpc.AspNetCore.Server.Reflection uses reflection to find the descriptor property. // DynamicallyAccessedMembersAttribute instructs the linker to never trim the members. private const DynamicallyAccessedMemberTypes ServiceBinderAccessibility = DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicProperties; - /// - /// Initializes a new instance of the class. - /// - /// The type the service bind method is defined on. - /// The name of the service bind method. - public BindServiceMethodAttribute([DynamicallyAccessedMembers(ServiceBinderAccessibility)] Type bindType, string bindMethodName) - { - BindType = bindType; - BindMethodName = bindMethodName; - } - /// /// Gets the type the service bind method is defined on. /// [DynamicallyAccessedMembers(ServiceBinderAccessibility)] - public Type BindType { get; } + public Type BindType { get; } = bindType; /// /// Gets the name of the service bind method. /// - public string BindMethodName { get; } + public string BindMethodName { get; } = bindMethodName; } diff --git a/src/Grpc.Core.Api/CallCredentials.cs b/src/Grpc.Core.Api/CallCredentials.cs index 086ecd8ca..f5be4b4ae 100644 --- a/src/Grpc.Core.Api/CallCredentials.cs +++ b/src/Grpc.Core.Api/CallCredentials.cs @@ -32,20 +32,14 @@ public abstract class CallCredentials /// /// credentials to compose /// The new CompositeCallCredentials - public static CallCredentials Compose(params CallCredentials[] credentials) - { - return new CompositeCallCredentials(credentials); - } + public static CallCredentials Compose(params CallCredentials[] credentials) => new CompositeCallCredentials(credentials); /// /// Creates a new instance of CallCredentials class from an /// interceptor that can attach metadata to outgoing calls. /// /// authentication interceptor - public static CallCredentials FromInterceptor(AsyncAuthInterceptor interceptor) - { - return new AsyncAuthInterceptorCredentials(interceptor); - } + public static CallCredentials FromInterceptor(AsyncAuthInterceptor interceptor) => new AsyncAuthInterceptorCredentials(interceptor); /// /// Populates call credentials configurator with this instance's configuration. @@ -64,23 +58,14 @@ public CompositeCallCredentials(CallCredentials[] credentials) } public override void InternalPopulateConfiguration(CallCredentialsConfiguratorBase configurator, object? state) - { - configurator.SetCompositeCredentials(state, credentials); - } + => configurator.SetCompositeCredentials(state, credentials); } - private class AsyncAuthInterceptorCredentials : CallCredentials + private class AsyncAuthInterceptorCredentials(AsyncAuthInterceptor interceptor) : CallCredentials { - readonly AsyncAuthInterceptor interceptor; - - public AsyncAuthInterceptorCredentials(AsyncAuthInterceptor interceptor) - { - this.interceptor = GrpcPreconditions.CheckNotNull(interceptor, nameof(interceptor)); - } + readonly AsyncAuthInterceptor interceptor = GrpcPreconditions.CheckNotNull(interceptor, nameof(interceptor)); public override void InternalPopulateConfiguration(CallCredentialsConfiguratorBase configurator, object? state) - { - configurator.SetAsyncAuthInterceptorCredentials(state, interceptor); - } + => configurator.SetAsyncAuthInterceptorCredentials(state, interceptor); } } diff --git a/src/Grpc.Core.Api/CallOptions.cs b/src/Grpc.Core.Api/CallOptions.cs index 97de48d32..fe0526cfa 100644 --- a/src/Grpc.Core.Api/CallOptions.cs +++ b/src/Grpc.Core.Api/CallOptions.cs @@ -60,18 +60,12 @@ public struct CallOptions /// /// Headers to send at the beginning of the call. /// - public Metadata? Headers - { - get { return headers; } - } + public Metadata? Headers => headers; /// /// Call deadline. /// - public DateTime? Deadline - { - get { return deadline; } - } + public DateTime? Deadline => deadline; /// /// Token that can be used for cancelling the call on the client side. @@ -82,52 +76,34 @@ public DateTime? Deadline /// happen (there is an inherent race), /// the call will finish with StatusCode.Cancelled status. /// - public CancellationToken CancellationToken - { - get { return cancellationToken; } - } + public CancellationToken CancellationToken => cancellationToken; /// /// Write options that will be used for this call. /// - public WriteOptions? WriteOptions - { - get { return this.writeOptions; } - } + public WriteOptions? WriteOptions => this.writeOptions; /// /// Token for propagating parent call context. /// - public ContextPropagationToken? PropagationToken - { - get { return this.propagationToken; } - } + public ContextPropagationToken? PropagationToken => this.propagationToken; /// /// Credentials to use for this call. /// - public CallCredentials? Credentials - { - get { return this.credentials; } - } + public CallCredentials? Credentials => this.credentials; /// /// If true and channel is in ChannelState.TransientFailure, the call will attempt waiting for the channel to recover /// instead of failing immediately (which is the default "FailFast" semantics). /// Note: experimental API that can change or be removed without any prior notice. /// - public bool IsWaitForReady - { - get { return (this.flags & CallFlags.WaitForReady) == CallFlags.WaitForReady; } - } + public bool IsWaitForReady => (this.flags & CallFlags.WaitForReady) == CallFlags.WaitForReady; /// /// Flags to use for this call. /// - internal CallFlags Flags - { - get { return this.flags; } - } + internal CallFlags Flags => this.flags; /// /// Returns new instance of with diff --git a/src/Grpc.Core.Api/ChannelBase.cs b/src/Grpc.Core.Api/ChannelBase.cs index d2ad12d18..108545ce7 100644 --- a/src/Grpc.Core.Api/ChannelBase.cs +++ b/src/Grpc.Core.Api/ChannelBase.cs @@ -33,16 +33,10 @@ public abstract class ChannelBase /// Initializes a new instance of class that connects to a specific host. /// /// Target of the channel. - protected ChannelBase(string target) - { - this.target = GrpcPreconditions.CheckNotNull(target, nameof(target)); - } + protected ChannelBase(string target) => this.target = GrpcPreconditions.CheckNotNull(target, nameof(target)); /// The original target used to create the channel. - public string Target - { - get { return this.target; } - } + public string Target => this.target; /// /// Create a new for the channel. @@ -62,13 +56,10 @@ public string Target /// before shutting down the channel to ensure channel shutdown won't impact /// the outcome of those remote calls. /// - public Task ShutdownAsync() - { - return ShutdownAsyncCore(); - } + public Task ShutdownAsync() => ShutdownAsyncCore(); /// Provides implementation of a non-virtual public member. - #pragma warning disable 1998 +#pragma warning disable 1998 protected virtual async Task ShutdownAsyncCore() { // default implementation is no-op for backwards compatibility, but all implementations diff --git a/src/Grpc.Core.Api/ChannelCredentials.cs b/src/Grpc.Core.Api/ChannelCredentials.cs index b2d227c3c..d46f88325 100644 --- a/src/Grpc.Core.Api/ChannelCredentials.cs +++ b/src/Grpc.Core.Api/ChannelCredentials.cs @@ -39,13 +39,7 @@ public ChannelCredentials() /// Returns instance of credentials that provides no security and /// will result in creating an unsecure channel with no encryption whatsoever. /// - public static ChannelCredentials Insecure - { - get - { - return InsecureInstance; - } - } + public static ChannelCredentials Insecure => InsecureInstance; /// /// Returns instance of credentials that provides SSL security. @@ -55,13 +49,7 @@ public static ChannelCredentials Insecure /// the secure SSL credentials. /// /// - public static ChannelCredentials SecureSsl - { - get - { - return SecureSslInstance; - } - } + public static ChannelCredentials SecureSsl => SecureSslInstance; /// /// Creates a new instance of ChannelCredentials class by composing @@ -71,9 +59,7 @@ public static ChannelCredentials SecureSsl /// Call credentials. /// The new composite ChannelCredentials public static ChannelCredentials Create(ChannelCredentials channelCredentials, CallCredentials callCredentials) - { - return new CompositeChannelCredentials(channelCredentials, callCredentials); - } + => new CompositeChannelCredentials(channelCredentials, callCredentials); /// /// Populates channel credentials configurator with this instance's configuration. @@ -94,35 +80,26 @@ public static ChannelCredentials Create(ChannelCredentials channelCredentials, C private sealed class InsecureCredentials : ChannelCredentials { public override void InternalPopulateConfiguration(ChannelCredentialsConfiguratorBase configurator, object state) - { - configurator.SetInsecureCredentials(state); - } + => configurator.SetInsecureCredentials(state); } /// /// Credentials that allow composing one object and /// one or more objects into a single . /// - private sealed class CompositeChannelCredentials : ChannelCredentials + /// + /// Initializes a new instance of CompositeChannelCredentials class. + /// The resulting credentials object will be composite of all the credentials specified as parameters. + /// + /// channelCredentials to compose + /// channelCredentials to compose + private sealed class CompositeChannelCredentials(ChannelCredentials channelCredentials, CallCredentials callCredentials) : ChannelCredentials { - readonly ChannelCredentials channelCredentials; - readonly CallCredentials callCredentials; - - /// - /// Initializes a new instance of CompositeChannelCredentials class. - /// The resulting credentials object will be composite of all the credentials specified as parameters. - /// - /// channelCredentials to compose - /// channelCredentials to compose - public CompositeChannelCredentials(ChannelCredentials channelCredentials, CallCredentials callCredentials) - { - this.channelCredentials = GrpcPreconditions.CheckNotNull(channelCredentials, nameof(channelCredentials)); - this.callCredentials = GrpcPreconditions.CheckNotNull(callCredentials, nameof(callCredentials)); - } + readonly ChannelCredentials channelCredentials = GrpcPreconditions.CheckNotNull(channelCredentials, + nameof(channelCredentials)); + readonly CallCredentials callCredentials = GrpcPreconditions.CheckNotNull(callCredentials, nameof(callCredentials)); public override void InternalPopulateConfiguration(ChannelCredentialsConfiguratorBase configurator, object state) - { - configurator.SetCompositeCredentials(state, channelCredentials, callCredentials); - } + => configurator.SetCompositeCredentials(state, channelCredentials, callCredentials); } } diff --git a/src/Grpc.Core.Api/ClientBase.cs b/src/Grpc.Core.Api/ClientBase.cs index 7379959b9..930905aec 100644 --- a/src/Grpc.Core.Api/ClientBase.cs +++ b/src/Grpc.Core.Api/ClientBase.cs @@ -134,18 +134,12 @@ public ClientBase(CallInvoker callInvoker) : this(new ClientBaseConfiguration(ca /// /// Gets the call invoker. /// - protected CallInvoker CallInvoker - { - get { return this.callInvoker; } - } + protected CallInvoker CallInvoker => this.callInvoker; /// /// Gets the configuration. /// - internal ClientBaseConfiguration Configuration - { - get { return this.configuration; } - } + internal ClientBaseConfiguration Configuration => this.configuration; internal string ServiceNameDebuggerToString() { @@ -158,14 +152,9 @@ internal string ServiceNameDebuggerToString() return $@"Service = ""{serviceName}"", "; } - internal sealed class ClientBaseDebugType + internal sealed class ClientBaseDebugType(ClientBase client) { - readonly ClientBase client; - - public ClientBaseDebugType(ClientBase client) - { - this.client = client; - } + readonly ClientBase client = client; public CallInvoker CallInvoker => client.CallInvoker; public string? Service => ClientDebuggerHelpers.GetServiceName(client.GetType()); @@ -180,17 +169,12 @@ public ClientBaseDebugType(ClientBase client) /// protected internal class ClientBaseConfiguration { - private class ClientBaseConfigurationInterceptor : Interceptor + /// + /// Creates a new instance of ClientBaseConfigurationInterceptor given the specified header and host interceptor function. + /// + private class ClientBaseConfigurationInterceptor(Func interceptor) : Interceptor { - readonly Func interceptor; - - /// - /// Creates a new instance of ClientBaseConfigurationInterceptor given the specified header and host interceptor function. - /// - public ClientBaseConfigurationInterceptor(Func interceptor) - { - this.interceptor = GrpcPreconditions.CheckNotNull(interceptor, nameof(interceptor)); - } + readonly Func interceptor = GrpcPreconditions.CheckNotNull(interceptor, nameof(interceptor)); private ClientInterceptorContext GetNewContext(ClientInterceptorContext context) where TRequest : class @@ -201,29 +185,19 @@ private ClientInterceptorContext GetNewContext(TRequest request, ClientInterceptorContext context, BlockingUnaryCallContinuation continuation) - { - return continuation(request, GetNewContext(context)); - } + => continuation(request, GetNewContext(context)); public override AsyncUnaryCall AsyncUnaryCall(TRequest request, ClientInterceptorContext context, AsyncUnaryCallContinuation continuation) - { - return continuation(request, GetNewContext(context)); - } + => continuation(request, GetNewContext(context)); public override AsyncServerStreamingCall AsyncServerStreamingCall(TRequest request, ClientInterceptorContext context, AsyncServerStreamingCallContinuation continuation) - { - return continuation(request, GetNewContext(context)); - } + => continuation(request, GetNewContext(context)); public override AsyncClientStreamingCall AsyncClientStreamingCall(ClientInterceptorContext context, AsyncClientStreamingCallContinuation continuation) - { - return continuation(GetNewContext(context)); - } + => continuation(GetNewContext(context)); public override AsyncDuplexStreamingCall AsyncDuplexStreamingCall(ClientInterceptorContext context, AsyncDuplexStreamingCallContinuation continuation) - { - return continuation(GetNewContext(context)); - } + => continuation(GetNewContext(context)); } internal struct ClientBaseConfigurationInfo @@ -247,10 +221,8 @@ internal ClientBaseConfiguration(CallInvoker undecoratedCallInvoker, string? hos this.host = host; } - internal CallInvoker CreateDecoratedCallInvoker() - { - return undecoratedCallInvoker.Intercept(new ClientBaseConfigurationInterceptor((method, host, options) => new ClientBaseConfigurationInfo(this.host, options))); - } + internal CallInvoker CreateDecoratedCallInvoker() => undecoratedCallInvoker.Intercept(new ClientBaseConfigurationInterceptor((method, host, options) + => new ClientBaseConfigurationInfo(this.host, options))); internal ClientBaseConfiguration WithHost(string host) { diff --git a/src/Grpc.Core.Api/ContextPropagationOptions.cs b/src/Grpc.Core.Api/ContextPropagationOptions.cs index 94ef75947..0c22280dc 100644 --- a/src/Grpc.Core.Api/ContextPropagationOptions.cs +++ b/src/Grpc.Core.Api/ContextPropagationOptions.cs @@ -23,36 +23,24 @@ namespace Grpc.Core; /// /// Options for . /// -public class ContextPropagationOptions +/// +/// Creates new context propagation options. +/// +/// If set to true parent call's deadline will be propagated to the child call. +/// If set to true parent call's cancellation token will be propagated to the child call. +public class ContextPropagationOptions(bool propagateDeadline = true, bool propagateCancellation = true) { /// /// The context propagation options that will be used by default. /// public static readonly ContextPropagationOptions Default = new ContextPropagationOptions(); - bool propagateDeadline; - bool propagateCancellation; + bool propagateDeadline = propagateDeadline; + bool propagateCancellation = propagateCancellation; - /// - /// Creates new context propagation options. - /// - /// If set to true parent call's deadline will be propagated to the child call. - /// If set to true parent call's cancellation token will be propagated to the child call. - public ContextPropagationOptions(bool propagateDeadline = true, bool propagateCancellation = true) - { - this.propagateDeadline = propagateDeadline; - this.propagateCancellation = propagateCancellation; - } - /// true if parent call's deadline should be propagated to the child call. - public bool IsPropagateDeadline - { - get { return this.propagateDeadline; } - } + public bool IsPropagateDeadline => this.propagateDeadline; /// true if parent call's cancellation token should be propagated to the child call. - public bool IsPropagateCancellation - { - get { return this.propagateCancellation; } - } + public bool IsPropagateCancellation => this.propagateCancellation; } diff --git a/src/Grpc.Core.Api/Interceptors/CallInvokerExtensions.cs b/src/Grpc.Core.Api/Interceptors/CallInvokerExtensions.cs index 81a27943a..4b97582bb 100644 --- a/src/Grpc.Core.Api/Interceptors/CallInvokerExtensions.cs +++ b/src/Grpc.Core.Api/Interceptors/CallInvokerExtensions.cs @@ -41,9 +41,7 @@ public static class CallInvokerExtensions /// in this case, the last interceptor added will be the first to take control. /// public static CallInvoker Intercept(this CallInvoker invoker, Interceptor interceptor) - { - return new InterceptingCallInvoker(invoker, interceptor); - } + => new InterceptingCallInvoker(invoker, interceptor); /// /// Returns a instance that intercepts @@ -90,9 +88,7 @@ public static CallInvoker Intercept(this CallInvoker invoker, params Interceptor /// in this case, the last interceptor added will be the first to take control. /// public static CallInvoker Intercept(this CallInvoker invoker, Func interceptor) - { - return new InterceptingCallInvoker(invoker, new MetadataInterceptor(interceptor)); - } + => new InterceptingCallInvoker(invoker, new MetadataInterceptor(interceptor)); private class MetadataInterceptor : Interceptor { @@ -115,28 +111,18 @@ private ClientInterceptorContext GetNewContext(TRequest request, ClientInterceptorContext context, BlockingUnaryCallContinuation continuation) - { - return continuation(request, GetNewContext(context)); - } + => continuation(request, GetNewContext(context)); public override AsyncUnaryCall AsyncUnaryCall(TRequest request, ClientInterceptorContext context, AsyncUnaryCallContinuation continuation) - { - return continuation(request, GetNewContext(context)); - } + => continuation(request, GetNewContext(context)); public override AsyncServerStreamingCall AsyncServerStreamingCall(TRequest request, ClientInterceptorContext context, AsyncServerStreamingCallContinuation continuation) - { - return continuation(request, GetNewContext(context)); - } + => continuation(request, GetNewContext(context)); public override AsyncClientStreamingCall AsyncClientStreamingCall(ClientInterceptorContext context, AsyncClientStreamingCallContinuation continuation) - { - return continuation(GetNewContext(context)); - } + => continuation(GetNewContext(context)); public override AsyncDuplexStreamingCall AsyncDuplexStreamingCall(ClientInterceptorContext context, AsyncDuplexStreamingCallContinuation continuation) - { - return continuation(GetNewContext(context)); - } + => continuation(GetNewContext(context)); } } diff --git a/src/Grpc.Core.Api/Interceptors/ChannelExtensions.cs b/src/Grpc.Core.Api/Interceptors/ChannelExtensions.cs index e4f137043..25cb4ce1f 100644 --- a/src/Grpc.Core.Api/Interceptors/ChannelExtensions.cs +++ b/src/Grpc.Core.Api/Interceptors/ChannelExtensions.cs @@ -39,9 +39,7 @@ public static class ChannelExtensions /// in this case, the last interceptor added will be the first to take control. /// public static CallInvoker Intercept(this ChannelBase channel, Interceptor interceptor) - { - return channel.CreateCallInvoker().Intercept(interceptor); - } + => channel.CreateCallInvoker().Intercept(interceptor); /// /// Returns a instance that intercepts diff --git a/src/Grpc.Core.Api/Interceptors/InterceptingCallInvoker.cs b/src/Grpc.Core.Api/Interceptors/InterceptingCallInvoker.cs index d1e39a77d..775ae3219 100644 --- a/src/Grpc.Core.Api/Interceptors/InterceptingCallInvoker.cs +++ b/src/Grpc.Core.Api/Interceptors/InterceptingCallInvoker.cs @@ -46,52 +46,42 @@ public InterceptingCallInvoker(CallInvoker invoker, Interceptor interceptor) /// Intercepts a simple blocking call with the registered interceptor. /// public override TResponse BlockingUnaryCall(Method method, string? host, CallOptions options, TRequest request) - { - return interceptor.BlockingUnaryCall( + => interceptor.BlockingUnaryCall( request, new ClientInterceptorContext(method, host, options), (req, ctx) => invoker.BlockingUnaryCall(ctx.Method, ctx.Host, ctx.Options, req)); - } /// /// Intercepts a simple asynchronous call with the registered interceptor. /// public override AsyncUnaryCall AsyncUnaryCall(Method method, string? host, CallOptions options, TRequest request) - { - return interceptor.AsyncUnaryCall( + => interceptor.AsyncUnaryCall( request, new ClientInterceptorContext(method, host, options), (req, ctx) => invoker.AsyncUnaryCall(ctx.Method, ctx.Host, ctx.Options, req)); - } /// /// Intercepts an asynchronous server streaming call with the registered interceptor. /// public override AsyncServerStreamingCall AsyncServerStreamingCall(Method method, string? host, CallOptions options, TRequest request) - { - return interceptor.AsyncServerStreamingCall( + => interceptor.AsyncServerStreamingCall( request, new ClientInterceptorContext(method, host, options), (req, ctx) => invoker.AsyncServerStreamingCall(ctx.Method, ctx.Host, ctx.Options, req)); - } /// /// Intercepts an asynchronous client streaming call with the registered interceptor. /// public override AsyncClientStreamingCall AsyncClientStreamingCall(Method method, string? host, CallOptions options) - { - return interceptor.AsyncClientStreamingCall( + => interceptor.AsyncClientStreamingCall( new ClientInterceptorContext(method, host, options), ctx => invoker.AsyncClientStreamingCall(ctx.Method, ctx.Host, ctx.Options)); - } /// /// Intercepts an asynchronous duplex streaming call with the registered interceptor. /// public override AsyncDuplexStreamingCall AsyncDuplexStreamingCall(Method method, string? host, CallOptions options) - { - return interceptor.AsyncDuplexStreamingCall( + => interceptor.AsyncDuplexStreamingCall( new ClientInterceptorContext(method, host, options), ctx => invoker.AsyncDuplexStreamingCall(ctx.Method, ctx.Host, ctx.Options)); - } } diff --git a/src/Grpc.Core.Api/Interceptors/Interceptor.cs b/src/Grpc.Core.Api/Interceptors/Interceptor.cs index 7cf89f879..767f49fa6 100644 --- a/src/Grpc.Core.Api/Interceptors/Interceptor.cs +++ b/src/Grpc.Core.Api/Interceptors/Interceptor.cs @@ -175,10 +175,7 @@ public delegate AsyncDuplexStreamingCall AsyncDuplexStreami /// public virtual TResponse BlockingUnaryCall(TRequest request, ClientInterceptorContext context, BlockingUnaryCallContinuation continuation) where TRequest : class - where TResponse : class - { - return continuation(request, context); - } + where TResponse : class => continuation(request, context); /// /// Intercepts an asynchronous invocation of a simple remote call. @@ -203,10 +200,7 @@ public virtual TResponse BlockingUnaryCall(TRequest request /// public virtual AsyncUnaryCall AsyncUnaryCall(TRequest request, ClientInterceptorContext context, AsyncUnaryCallContinuation continuation) where TRequest : class - where TResponse : class - { - return continuation(request, context); - } + where TResponse : class => continuation(request, context); /// /// Intercepts an asynchronous invocation of a streaming remote call. @@ -231,10 +225,7 @@ public virtual AsyncUnaryCall AsyncUnaryCall(TRe /// public virtual AsyncServerStreamingCall AsyncServerStreamingCall(TRequest request, ClientInterceptorContext context, AsyncServerStreamingCallContinuation continuation) where TRequest : class - where TResponse : class - { - return continuation(request, context); - } + where TResponse : class => continuation(request, context); /// /// Intercepts an asynchronous invocation of a client streaming call. @@ -258,10 +249,7 @@ public virtual AsyncServerStreamingCall AsyncServerStreamingCall public virtual AsyncClientStreamingCall AsyncClientStreamingCall(ClientInterceptorContext context, AsyncClientStreamingCallContinuation continuation) where TRequest : class - where TResponse : class - { - return continuation(context); - } + where TResponse : class => continuation(context); /// /// Intercepts an asynchronous invocation of a duplex streaming call. @@ -285,10 +273,7 @@ public virtual AsyncClientStreamingCall AsyncClientStreamin /// public virtual AsyncDuplexStreamingCall AsyncDuplexStreamingCall(ClientInterceptorContext context, AsyncDuplexStreamingCallContinuation continuation) where TRequest : class - where TResponse : class - { - return continuation(context); - } + where TResponse : class => continuation(context); /// /// Server-side handler for intercepting and incoming unary call. @@ -314,10 +299,7 @@ public virtual AsyncDuplexStreamingCall AsyncDuplexStreamin /// public virtual Task UnaryServerHandler(TRequest request, ServerCallContext context, UnaryServerMethod continuation) where TRequest : class - where TResponse : class - { - return continuation(request, context); - } + where TResponse : class => continuation(request, context); /// /// Server-side handler for intercepting client streaming call. @@ -345,10 +327,7 @@ public virtual Task UnaryServerHandler(TRequest /// public virtual Task ClientStreamingServerHandler(IAsyncStreamReader requestStream, ServerCallContext context, ClientStreamingServerMethod continuation) where TRequest : class - where TResponse : class - { - return continuation(requestStream, context); - } + where TResponse : class => continuation(requestStream, context); /// /// Server-side handler for intercepting server streaming call. @@ -371,10 +350,7 @@ public virtual Task ClientStreamingServerHandler /// public virtual Task ServerStreamingServerHandler(TRequest request, IServerStreamWriter responseStream, ServerCallContext context, ServerStreamingServerMethod continuation) where TRequest : class - where TResponse : class - { - return continuation(request, responseStream, context); - } + where TResponse : class => continuation(request, responseStream, context); /// /// Server-side handler for intercepting bidirectional streaming calls. @@ -397,8 +373,5 @@ public virtual Task ServerStreamingServerHandler(TRequest r /// public virtual Task DuplexStreamingServerHandler(IAsyncStreamReader requestStream, IServerStreamWriter responseStream, ServerCallContext context, DuplexStreamingServerMethod continuation) where TRequest : class - where TResponse : class - { - return continuation(requestStream, responseStream, context); - } + where TResponse : class => continuation(requestStream, responseStream, context); } diff --git a/src/Grpc.Core.Api/Internal/CallDebuggerHelpers.cs b/src/Grpc.Core.Api/Internal/CallDebuggerHelpers.cs index a7e5a0d30..679f50067 100644 --- a/src/Grpc.Core.Api/Internal/CallDebuggerHelpers.cs +++ b/src/Grpc.Core.Api/Internal/CallDebuggerHelpers.cs @@ -104,14 +104,9 @@ public static string DebuggerToString(AsyncCallState callState) } [DebuggerDisplay("{FullName,nq}")] -internal sealed class CallDebuggerMethodDebugView +internal sealed class CallDebuggerMethodDebugView(IMethod method) { - private readonly IMethod _method; - - public CallDebuggerMethodDebugView(IMethod method) - { - _method = method; - } + private readonly IMethod _method = method; public MethodType Type => _method.Type; public string ServiceName => _method.ServiceName; diff --git a/src/Grpc.Core.Api/KeyCertificatePair.cs b/src/Grpc.Core.Api/KeyCertificatePair.cs index 1c0d28515..addf31e0b 100644 --- a/src/Grpc.Core.Api/KeyCertificatePair.cs +++ b/src/Grpc.Core.Api/KeyCertificatePair.cs @@ -27,41 +27,23 @@ namespace Grpc.Core; /// /// Key certificate pair (in PEM encoding). /// -public sealed class KeyCertificatePair +/// +/// Creates a new certificate chain - private key pair. +/// +/// PEM encoded certificate chain. +/// PEM encoded private key. +public sealed class KeyCertificatePair(string certificateChain, string privateKey) { - readonly string certificateChain; - readonly string privateKey; - - /// - /// Creates a new certificate chain - private key pair. - /// - /// PEM encoded certificate chain. - /// PEM encoded private key. - public KeyCertificatePair(string certificateChain, string privateKey) - { - this.certificateChain = GrpcPreconditions.CheckNotNull(certificateChain, "certificateChain"); - this.privateKey = GrpcPreconditions.CheckNotNull(privateKey, "privateKey"); - } + readonly string certificateChain = GrpcPreconditions.CheckNotNull(certificateChain, "certificateChain"); + readonly string privateKey = GrpcPreconditions.CheckNotNull(privateKey, "privateKey"); /// /// PEM encoded certificate chain. /// - public string CertificateChain - { - get - { - return certificateChain; - } - } + public string CertificateChain => certificateChain; /// /// PEM encoded private key. /// - public string PrivateKey - { - get - { - return privateKey; - } - } + public string PrivateKey => privateKey; } diff --git a/src/Grpc.Core.Api/Marshaller.cs b/src/Grpc.Core.Api/Marshaller.cs index b3de07c94..08c192c1b 100644 --- a/src/Grpc.Core.Api/Marshaller.cs +++ b/src/Grpc.Core.Api/Marshaller.cs @@ -95,10 +95,7 @@ private void EmulateContextualSerializer(T message, SerializationContext context } // for backward compatibility, emulate the contextual deserializer using the simple one - private T EmulateContextualDeserializer(DeserializationContext context) - { - return this.deserializer(context.PayloadAsNewBuffer()); - } + private T EmulateContextualDeserializer(DeserializationContext context) => this.deserializer(context.PayloadAsNewBuffer()); } /// @@ -110,28 +107,18 @@ public static class Marshallers /// Creates a marshaller from specified serializer and deserializer. /// public static Marshaller Create(Func serializer, Func deserializer) - { - return new Marshaller(serializer, deserializer); - } + => new Marshaller(serializer, deserializer); /// /// Creates a marshaller from specified contextual serializer and deserializer. /// Note: This method is part of an experimental API that can change or be removed without any prior notice. /// public static Marshaller Create(Action serializer, Func deserializer) - { - return new Marshaller(serializer, deserializer); - } + => new Marshaller(serializer, deserializer); /// /// Returns a marshaller for string type. This is useful for testing. /// public static Marshaller StringMarshaller - { - get - { - return new Marshaller(System.Text.Encoding.UTF8.GetBytes, - System.Text.Encoding.UTF8.GetString); - } - } + => new Marshaller(System.Text.Encoding.UTF8.GetBytes,System.Text.Encoding.UTF8.GetString); } diff --git a/src/Grpc.Core.Api/Metadata.cs b/src/Grpc.Core.Api/Metadata.cs index 523928dae..e6e395e3e 100644 --- a/src/Grpc.Core.Api/Metadata.cs +++ b/src/Grpc.Core.Api/Metadata.cs @@ -66,10 +66,7 @@ public sealed class Metadata : IList /// /// Initializes a new instance of Metadata. /// - public Metadata() - { - this.entries = new List(); - } + public Metadata() => this.entries = new List(); /// /// Makes this object read-only. @@ -103,20 +100,14 @@ internal Metadata Freeze() /// If the metadata entry is binary then an exception is thrown. /// If there are no matching entries then null is returned. /// - public string? GetValue(string key) - { - return Get(key)?.Value; - } + public string? GetValue(string key) => Get(key)?.Value; /// /// Gets the bytes value of the last metadata entry with the specified key. /// If the metadata entry is not binary the string value will be returned as ASCII encoded bytes. /// If there are no matching entries then null is returned. /// - public byte[]? GetValueBytes(string key) - { - return Get(key)?.ValueBytes; - } + public byte[]? GetValueBytes(string key) => Get(key)?.ValueBytes; /// /// Gets all metadata entries with the specified key. @@ -137,20 +128,14 @@ public IEnumerable GetAll(string key) /// /// Metadata key. Gets converted to lowercase. Must not use -bin suffix indicating a binary-valued metadata entry. Can only contain lowercase alphanumeric characters, underscores, hyphens, and dots. /// Value string. Only ASCII characters are allowed. - public void Add(string key, string value) - { - Add(new Entry(key, value)); - } + public void Add(string key, string value) => Add(new Entry(key, value)); /// /// Adds a new binary-valued metadata entry. /// /// Metadata key. Gets converted to lowercase. Needs to have -bin suffix indicating a binary-valued metadata entry. The binary header suffix can be added to the key with . Can only contain lowercase alphanumeric characters, underscores, hyphens, and dots. /// Value bytes. - public void Add(string key, byte[] valueBytes) - { - Add(new Entry(key, valueBytes)); - } + public void Add(string key, byte[] valueBytes) => Add(new Entry(key, valueBytes)); #region IList members @@ -328,13 +313,7 @@ public Entry(string key, string value) /// /// Gets the metadata entry key. /// - public string Key - { - get - { - return this.key; - } - } + public string Key => this.key; /// /// Gets the binary value of this metadata entry. @@ -372,13 +351,7 @@ public string Value /// /// Returns true if this entry is a binary-value entry. /// - public bool IsBinary - { - get - { - return value == null; - } - } + public bool IsBinary => value == null; /// /// Returns a that represents the current . @@ -397,20 +370,15 @@ public override string ToString() /// Gets the serialized value for this entry. For binary metadata entries, this leaks /// the internal valueBytes byte array and caller must not change contents of it. /// - internal byte[] GetSerializedValueUnsafe() - { - return valueBytes ?? EncodingASCII.GetBytes(value!); - } + internal byte[] GetSerializedValueUnsafe() => valueBytes ?? EncodingASCII.GetBytes(value!); - internal bool KeyEqualsIgnoreCase(string key) - { + internal bool KeyEqualsIgnoreCase(string key) => // NormalizeKey() uses ToLowerInvariant() to lowercase keys, so we'd like to use the same invariant culture // for comparisons to get valid results. StringComparison.InvariantCultureIgnoreCase isn't available // on all the frameworks we're targeting, but since we know that the Entry's key has already // been checked by IsValidKey and it only contains a subset of ASCII, using StringComparison.OrdinalIgnoreCase // is also fine. - return string.Equals(this.key, key, StringComparison.OrdinalIgnoreCase); - } + string.Equals(this.key, key, StringComparison.OrdinalIgnoreCase); /// /// Creates a binary value or ascii value metadata entry from data received from the native layer. @@ -515,14 +483,9 @@ private string DebuggerToString() return debugText; } - private sealed class MetadataDebugView + private sealed class MetadataDebugView(Metadata metadata) { - private readonly Metadata _metadata; - - public MetadataDebugView(Metadata metadata) - { - _metadata = metadata; - } + private readonly Metadata _metadata = metadata; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public Entry[] Items => _metadata.ToArray(); diff --git a/src/Grpc.Core.Api/Method.cs b/src/Grpc.Core.Api/Method.cs index 7c43e5fb3..d2caf3d1a 100644 --- a/src/Grpc.Core.Api/Method.cs +++ b/src/Grpc.Core.Api/Method.cs @@ -72,106 +72,59 @@ public interface IMethod /// /// Request message type for this method. /// Response message type for this method. +/// +/// Initializes a new instance of the Method class. +/// +/// Type of method. +/// Name of service this method belongs to. +/// Unqualified name of the method. +/// Marshaller used for request messages. +/// Marshaller used for response messages. [DebuggerDisplay("Name = {Name}, ServiceName = {ServiceName}, Type = {Type}")] -public class Method : IMethod +public class Method(MethodType type, + string serviceName, string name, Marshaller requestMarshaller, + Marshaller responseMarshaller) : IMethod { - readonly MethodType type; - readonly string serviceName; - readonly string name; - readonly Marshaller requestMarshaller; - readonly Marshaller responseMarshaller; - readonly string fullName; - - /// - /// Initializes a new instance of the Method class. - /// - /// Type of method. - /// Name of service this method belongs to. - /// Unqualified name of the method. - /// Marshaller used for request messages. - /// Marshaller used for response messages. - public Method(MethodType type, string serviceName, string name, Marshaller requestMarshaller, Marshaller responseMarshaller) - { - this.type = type; - this.serviceName = GrpcPreconditions.CheckNotNull(serviceName, "serviceName"); - this.name = GrpcPreconditions.CheckNotNull(name, "name"); - this.requestMarshaller = GrpcPreconditions.CheckNotNull(requestMarshaller, "requestMarshaller"); - this.responseMarshaller = GrpcPreconditions.CheckNotNull(responseMarshaller, "responseMarshaller"); - this.fullName = GetFullName(serviceName, name); - } + readonly MethodType type = type; + readonly string serviceName = GrpcPreconditions.CheckNotNull(serviceName, "serviceName"); + readonly string name = GrpcPreconditions.CheckNotNull(name, "name"); + readonly Marshaller requestMarshaller = GrpcPreconditions.CheckNotNull(requestMarshaller, "requestMarshaller"); + readonly Marshaller responseMarshaller = GrpcPreconditions.CheckNotNull(responseMarshaller, "responseMarshaller"); + readonly string fullName = GetFullName(serviceName, name); /// /// Gets the type of the method. /// - public MethodType Type - { - get - { - return this.type; - } - } - + public MethodType Type => this.type; + /// /// Gets the name of the service to which this method belongs. /// - public string ServiceName - { - get - { - return this.serviceName; - } - } + public string ServiceName => this.serviceName; /// /// Gets the unqualified name of the method. /// - public string Name - { - get - { - return this.name; - } - } + public string Name => this.name; /// /// Gets the marshaller used for request messages. /// - public Marshaller RequestMarshaller - { - get - { - return this.requestMarshaller; - } - } + public Marshaller RequestMarshaller => this.requestMarshaller; /// /// Gets the marshaller used for response messages. /// - public Marshaller ResponseMarshaller - { - get - { - return this.responseMarshaller; - } - } - + public Marshaller ResponseMarshaller => this.responseMarshaller; + /// /// Gets the fully qualified name of the method. On the server side, methods are dispatched /// based on this name. /// - public string FullName - { - get - { - return this.fullName; - } - } + public string FullName => this.fullName; /// /// Gets full name of the method including the service name. /// - internal static string GetFullName(string serviceName, string methodName) - { - return "/" + serviceName + "/" + methodName; - } + internal static string GetFullName(string serviceName, string methodName) => "/" + serviceName + "/" + methodName; } diff --git a/src/Grpc.Core.Api/RpcException.cs b/src/Grpc.Core.Api/RpcException.cs index 867f02323..b5e6a4331 100644 --- a/src/Grpc.Core.Api/RpcException.cs +++ b/src/Grpc.Core.Api/RpcException.cs @@ -74,35 +74,17 @@ public RpcException(Status status, Metadata trailers, string message) : base(mes /// /// Resulting status of the call. /// - public Status Status - { - get - { - return status; - } - } + public Status Status => status; /// /// Returns the status code of the call, as a convenient alternative to Status.StatusCode. /// - public StatusCode StatusCode - { - get - { - return status.StatusCode; - } - } + public StatusCode StatusCode => status.StatusCode; /// /// Gets the call trailing metadata. /// Trailers only have meaningful content for client-side calls (in which case they represent the trailing metadata sent by the server when closing the call). /// Instances of RpcException thrown by the server-side part of the stack will have trailers always set to empty. /// - public Metadata Trailers - { - get - { - return trailers; - } - } + public Metadata Trailers => trailers; } diff --git a/src/Grpc.Core.Api/ServerCallContext.cs b/src/Grpc.Core.Api/ServerCallContext.cs index 2136d4ba1..13877af3f 100644 --- a/src/Grpc.Core.Api/ServerCallContext.cs +++ b/src/Grpc.Core.Api/ServerCallContext.cs @@ -44,18 +44,12 @@ protected ServerCallContext() /// /// The response headers to send. /// The task that finished once response headers have been written. - public Task WriteResponseHeadersAsync(Metadata responseHeaders) - { - return WriteResponseHeadersAsyncCore(responseHeaders); - } + public Task WriteResponseHeadersAsync(Metadata responseHeaders) => WriteResponseHeadersAsyncCore(responseHeaders); /// /// Creates a propagation token to be used to propagate call context to a child call. /// - public ContextPropagationToken CreatePropagationToken(ContextPropagationOptions? options = null) - { - return CreatePropagationTokenCore(options); - } + public ContextPropagationToken CreatePropagationToken(ContextPropagationOptions? options = null) => CreatePropagationTokenCore(options); /// Name of method called in this RPC. public string Method => MethodCore; diff --git a/src/Grpc.Core.Api/ServerServiceDefinition.cs b/src/Grpc.Core.Api/ServerServiceDefinition.cs index cc5f1e6da..904fb178a 100644 --- a/src/Grpc.Core.Api/ServerServiceDefinition.cs +++ b/src/Grpc.Core.Api/ServerServiceDefinition.cs @@ -31,9 +31,7 @@ public class ServerServiceDefinition readonly IReadOnlyList> addMethodActions; internal ServerServiceDefinition(List> addMethodActions) - { - this.addMethodActions = addMethodActions.AsReadOnly(); - } + => this.addMethodActions = addMethodActions.AsReadOnly(); /// /// Forwards all the previously stored AddMethod calls to the service binder. @@ -50,10 +48,7 @@ internal void BindService(ServiceBinderBase serviceBinder) /// Creates a new builder object for ServerServiceDefinition. /// /// The builder object. - public static Builder CreateBuilder() - { - return new Builder(); - } + public static Builder CreateBuilder() => new Builder(); /// /// Builder class for . @@ -152,9 +147,6 @@ public Builder AddMethod( /// Creates an immutable ServerServiceDefinition from this builder. /// /// The ServerServiceDefinition object. - public ServerServiceDefinition Build() - { - return new ServerServiceDefinition(addMethodActions); - } + public ServerServiceDefinition Build() => new ServerServiceDefinition(addMethodActions); } } diff --git a/src/Grpc.Core.Api/SslCredentials.cs b/src/Grpc.Core.Api/SslCredentials.cs index 54a9a87d3..2d526a11b 100644 --- a/src/Grpc.Core.Api/SslCredentials.cs +++ b/src/Grpc.Core.Api/SslCredentials.cs @@ -86,34 +86,20 @@ public SslCredentials(string? rootCertificates, KeyCertificatePair? keyCertifica /// /// PEM encoding of the server root certificates. /// - public string? RootCertificates - { - get - { - return this.rootCertificates; - } - } + public string? RootCertificates => this.rootCertificates; /// /// Client side key and certificate pair. /// If null, client will not use key and certificate pair. /// - public KeyCertificatePair? KeyCertificatePair - { - get - { - return this.keyCertificatePair; - } - } + public KeyCertificatePair? KeyCertificatePair => this.keyCertificatePair; /// /// Populates channel credentials configurator with this instance's configuration. /// End users never need to invoke this method as it is part of internal implementation. /// public override void InternalPopulateConfiguration(ChannelCredentialsConfiguratorBase configurator, object state) - { - configurator.SetSslCredentials(state, rootCertificates, keyCertificatePair, verifyPeerCallback); - } + => configurator.SetSslCredentials(state, rootCertificates, keyCertificatePair, verifyPeerCallback); internal override bool IsComposable => true; } diff --git a/src/Grpc.Core.Api/Status.cs b/src/Grpc.Core.Api/Status.cs index 45d795562..297fec697 100644 --- a/src/Grpc.Core.Api/Status.cs +++ b/src/Grpc.Core.Api/Status.cs @@ -23,8 +23,17 @@ namespace Grpc.Core; /// /// Represents RPC result, which consists of and an optional detail string. /// +/// +/// Creates a new instance of Status. +/// Users should not use this constructor, except for creating instances for testing. +/// The debug error string should only be populated by gRPC internals. +/// Note: experimental API that can change or be removed without any prior notice. +/// +/// Status code. +/// Detail. +/// Optional internal error details. [DebuggerDisplay("{DebuggerToString(),nq}")] -public struct Status +public struct Status(StatusCode statusCode, string detail, Exception? debugException) { /// /// Default result of a successful RPC. StatusCode=OK, empty details message. @@ -45,31 +54,15 @@ public Status(StatusCode statusCode, string detail) : this(statusCode, detail, n { } - /// - /// Creates a new instance of Status. - /// Users should not use this constructor, except for creating instances for testing. - /// The debug error string should only be populated by gRPC internals. - /// Note: experimental API that can change or be removed without any prior notice. - /// - /// Status code. - /// Detail. - /// Optional internal error details. - public Status(StatusCode statusCode, string detail, Exception? debugException) - { - StatusCode = statusCode; - Detail = detail; - DebugException = debugException; - } - /// /// Gets the gRPC status code. OK indicates success, all other values indicate an error. /// - public StatusCode StatusCode { get; } + public StatusCode StatusCode { get; } = statusCode; /// /// Gets the detail. /// - public string Detail { get; } + public string Detail { get; } = detail; /// /// In case of an error, this field may contain additional error details to help with debugging. @@ -81,7 +74,7 @@ public Status(StatusCode statusCode, string detail, Exception? debugException) /// why the connection to the server has failed. /// Note: experimental API that can change or be removed without any prior notice. /// - public Exception? DebugException { get; } + public Exception? DebugException { get; } = debugException; /// /// Returns a that represents the current . diff --git a/src/Grpc.Core.Api/Utils/EncodingExtensions.cs b/src/Grpc.Core.Api/Utils/EncodingExtensions.cs index aa7b4a13f..84a96633b 100644 --- a/src/Grpc.Core.Api/Utils/EncodingExtensions.cs +++ b/src/Grpc.Core.Api/Utils/EncodingExtensions.cs @@ -28,8 +28,6 @@ internal static class EncodingExtensions /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe string GetString(this Encoding encoding, IntPtr ptr, int len) - { - return len == 0 ? "" : encoding.GetString((byte*)ptr.ToPointer(), len); - } + => len == 0 ? "" : encoding.GetString((byte*)ptr.ToPointer(), len); } diff --git a/src/Grpc.Core.Api/WriteOptions.cs b/src/Grpc.Core.Api/WriteOptions.cs index c4d78de64..b91b3874f 100644 --- a/src/Grpc.Core.Api/WriteOptions.cs +++ b/src/Grpc.Core.Api/WriteOptions.cs @@ -42,32 +42,21 @@ public enum WriteFlags /// /// Options for write operations. /// -public class WriteOptions +/// +/// Initializes a new instance of WriteOptions class. +/// +/// The write flags. +public class WriteOptions(WriteFlags flags = default(WriteFlags)) { /// /// Default write options. /// public static readonly WriteOptions Default = new WriteOptions(); - private readonly WriteFlags flags; - - /// - /// Initializes a new instance of WriteOptions class. - /// - /// The write flags. - public WriteOptions(WriteFlags flags = default(WriteFlags)) - { - this.flags = flags; - } + private readonly WriteFlags flags = flags; /// /// Gets the write flags. /// - public WriteFlags Flags - { - get - { - return this.flags; - } - } + public WriteFlags Flags => this.flags; }