Ejemplo n.º 1
0
        public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>(TRequest request,
                                                                                        ClientInterceptorContext <TRequest, TResponse> context,
                                                                                        AsyncUnaryCallContinuation <TRequest, TResponse> continuation)
        {
            var pollyRetry = Policy <AsyncUnaryCall <TResponse> > .Handle <Exception>()
                             .Retry(RetryCount);

            var pollyBulk = Policy.Bulkhead <AsyncUnaryCall <TResponse> >(MaxBulkhead);

            var pollyFallback = Policy <AsyncUnaryCall <TResponse> > .Handle <Exception>()
                                .Fallback(item =>
            {
                return(!string.IsNullOrEmpty(FallbackMethod)
                        ? UseNewMethod <TResponse>(new object[] { request })
                        : null);
            });

            var timeoutPolly = Policy.Timeout <AsyncUnaryCall <TResponse> >(30);

            var policy = Policy.Wrap(pollyFallback, pollyRetry, timeoutPolly, pollyBulk);

            var response = policy.Execute(() =>
            {
                var responseCon = continuation(request, context);
                var call        = new AsyncUnaryCall <TResponse>(responseCon.ResponseAsync,
                                                                 responseCon.ResponseHeadersAsync,
                                                                 responseCon.GetStatus,
                                                                 responseCon.GetTrailers,
                                                                 responseCon.Dispose);

                return(call);
            });

            return(response);
        }
Ejemplo n.º 2
0
 public UnaryResult(AsyncUnaryCall <byte[]> inner, IFormatterResolver resolver)
 {
     this.hasRawValue = false;
     this.rawValue    = default(TResponse);
     this.inner       = inner;
     this.resolver    = resolver;
 }
Ejemplo n.º 3
0
        public override AsyncUnaryCall <AccountRegistrationResponse> RegisterAccountAsync(AccountRegistrationRequest request, CallOptions options)
        {
            AsyncUnaryCall <AccountRegistrationResponse> response = base.RegisterAccountAsync(request, options);

            response.ResponseAsync.ContinueWith((authResponse) => { Auth.Login(authResponse.Result.Token); });
            return(response);
        }
        /// <summary>
        /// Intercepts an asynchronous invocation of a simple remote call.
        /// </summary>
        /// <param name="request">The request message of the invocation.</param>
        /// <param name="context">The <see cref="ClientInterceptorContext{TRequest, TResponse}" />
        /// associated with the current invocation.</param>
        /// <param name="continuation">The callback that continues the invocation process.
        /// This can be invoked zero or more times by the interceptor.
        /// The interceptor can invoke the continuation passing the given
        /// request value and context arguments, or substitute them as it sees fit.</param>
        /// <returns>
        /// An instance of <see cref="AsyncUnaryCall{TResponse}" />
        /// representing an asynchronous unary invocation.
        /// The interceptor can simply return the return value of the
        /// continuation delegate passed to it intact, or construct its
        /// own substitute as it sees fit.
        /// </returns>
        public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>(
            TRequest request, ClientInterceptorContext <TRequest, TResponse> context,
            AsyncUnaryCallContinuation <TRequest, TResponse> continuation)
        {
            AsyncUnaryCall <TResponse> call = continuation(request, context);
            Task t = call.ResponseAsync.ContinueWith(
                delegate(Task <TResponse> oldTask)
            {
                // Generating log entry is expensive, so let's do that only if the log source
                // has been configured to do so.
                if (TraceUtilities.ShouldGenerateRequestLogs())
                {
                    LogEntry logEntry = new LogEntry()
                    {
                        Host            = Config.ServerUrl,
                        Method          = context.Method.FullName,
                        RequestHeaders  = context.Options.Headers,
                        Request         = request,
                        ResponseHeaders = GetResponseHeader(call),
                        Response        = (oldTask.IsFaulted) ? default(TResponse) : oldTask.Result,
                        Exception       = GetGoogleAdsException(oldTask.Exception),
                        IsFailure       = oldTask.IsFaulted,
                        CustomerId      = GetCustomerId(request),
                        PartialFailures = (oldTask.IsFaulted)? "" :
                                          GetPartialFailures(oldTask.Result)
                    };
                    OnLogEventAvailable?.Invoke(this, logEntry);
                }
            });

            t.Wait();
            return(call);
        }
        /// <exclude />
        public static async Task <T> GetAsyncUnaryCallResult <T>(AsyncUnaryCall <Message <T> > call, CallContext?context, CancellationToken token)
        {
            Message <T> result;

            using (call)
            {
                if (context != null && !token.IsCancellationRequested)
                {
                    var headers = await call.ResponseHeadersAsync.ConfigureAwait(false);

                    context.ServerResponse = new ServerResponse(
                        headers,
                        call.GetStatus,
                        call.GetTrailers);
                }

                result = await call;

                if (context != null && !token.IsCancellationRequested)
                {
                    context.ServerResponse = new ServerResponse(
                        context.ResponseHeaders !,
                        call.GetStatus(),
                        call.GetTrailers());
                }
            }

            return(result.Value1);
        }
Ejemplo n.º 6
0
 public UnaryResult(TResponse rawValue)
 {
     this.hasRawValue = true;
     this.rawValue    = rawValue;
     this.inner       = null;
     this.resolver    = null;
 }
        /// <exclude />
        public static async Task AsyncUnaryCallWait(AsyncUnaryCall <Message> call, CallContext?context, CancellationToken token)
        {
            using (call)
            {
                if (context != null && !token.IsCancellationRequested)
                {
                    var headers = await call.ResponseHeadersAsync.ConfigureAwait(false);

                    context.ServerResponse = new ServerResponse(
                        headers,
                        call.GetStatus,
                        call.GetTrailers);
                }

                await call;

                if (context != null && !token.IsCancellationRequested)
                {
                    context.ServerResponse = new ServerResponse(
                        context.ResponseHeaders !,
                        call.GetStatus(),
                        call.GetTrailers());
                }
            }
        }
Ejemplo n.º 8
0
        public override AsyncUnaryCall <AuthorizationResponse> LoginAsync(AuthorizationRequest request, CallOptions options)
        {
            AsyncUnaryCall <AuthorizationResponse> response = base.LoginAsync(request, options);

            response.ResponseAsync.ContinueWith((authResponse) => { Auth.Login(authResponse.Result.Token); });
            return(response);
        }
Ejemplo n.º 9
0
        public async Task Can_access_validation_Errors_depfree()
        {
            AsyncUnaryCall <EmptyResponse> call = null;

            try
            {
                var client = CreateClient();

                call = client.PutUpdateTodoAsync(new UpdateTodo {
                    Id    = 0,
                    Title = "",
                    Order = -1,
                });
                await call;
            }
            catch (RpcException ex)
            {
                Assert.That(ex.Status.Detail, Is.EqualTo("GreaterThan"));
                Assert.That(ex.StatusCode, Is.EqualTo(StatusCode.Internal));

                var headers    = await call.ResponseHeadersAsync;
                var httpStatus = int.Parse(headers.First(x => x.Key == "httpstatus").Value);
                Assert.That(httpStatus, Is.EqualTo(400));

                var statusBytes = headers.First(x => x.Key == "responsestatus-bin").ValueBytes;
                var status      = ResponseStatus.Parser.ParseFrom(statusBytes);
                AssertUpdateTodoValidationErrors(status);
            }
        }
        public void TestAsyncUnaryCallWithPartialFailure()
        {
            GoogleAdsConfig config  = new GoogleAdsConfig();
            LoggingHandler  handler = new LoggingHandler(config);

            handler.WriteSummaryLogs = delegate(LogEntry logEntry)
            {
                Assert.AreEqual(config.ServerUrl, logEntry.Host);
                Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method);
                CompareMetadata(TEST_REQUEST_METADATA, logEntry.RequestHeaders);
                Assert.False(logEntry.IsFailure);
            };
            handler.WriteDetailedLogs = delegate(LogEntry logEntry)
            {
                Assert.AreEqual(config.ServerUrl, logEntry.Host);
                Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method);
                CompareMetadata(TEST_REQUEST_METADATA, logEntry.RequestHeaders);
                CompareMetadata(TEST_RESPONSE_METADATA, logEntry.ResponseHeaders);
                Assert.AreSame(TEST_REQUEST, logEntry.Request);
                Assert.AreSame(TEST_RESPONSE_PARTIAL_FAILURES, logEntry.Response);
                Assert.AreEqual(TEST_CUSTOMER_ID, logEntry.CustomerId);
                Assert.False(logEntry.IsFailure);
                Assert.AreEqual(TEST_PARTIAL_FAILURE_TEXT, logEntry.PartialFailures);
            };
            ClientInterceptorContext <HelloRequest, HelloResponse> context =
                GetClientInterceptorContext();
            AsyncUnaryCall <HelloResponse> call =
                ContinuationWithPartialFailures(TEST_REQUEST, context);

            handler.HandleAsyncUnaryLogging(TEST_REQUEST, context, call.ResponseAsync, call);
        }
Ejemplo n.º 11
0
        public void ExecuteSqlAsync()
        {
            Session session;

            session = client.CreateSession(
                new CreateSessionRequest {
                Database = DatabaseUrl
            });
            Assert.IsNotNull(session);
            AssertAffinityCount(1);

            AsyncUnaryCall <ResultSet> call = client.ExecuteSqlAsync(
                new ExecuteSqlRequest
            {
                Session = session.Name,
                Sql     = string.Format("select id, data from {0}", TableName)
            });

            AssertAffinityCount(1, expectedActiveStreamCount: 1);

            ResultSet resultSet = call.ResponseAsync.Result;

            AssertAffinityCount(1);

            Assert.IsNotNull(resultSet);
            Assert.AreEqual(1, resultSet.Rows.Count);
            Assert.AreEqual(ColumnId, resultSet.Rows[0].Values[0].StringValue);

            client.DeleteSession(new DeleteSessionRequest {
                Name = session.Name
            });
            AssertAffinityCount(0);
        }
Ejemplo n.º 12
0
        public void MutateRowAsync()
        {
            MutateRowRequest mutateRowRequest = new MutateRowRequest
            {
                TableName = TableName,
                RowKey    = ByteString.CopyFromUtf8(RowKey),
            };

            Mutation mutation = new Mutation
            {
                SetCell = new Mutation.Types.SetCell
                {
                    FamilyName      = ColumnFamily,
                    ColumnQualifier = ByteString.CopyFromUtf8(ColumnQualifier),
                    Value           = ByteString.CopyFromUtf8(TestValue),
                }
            };

            mutateRowRequest.Mutations.Add(mutation);

            AsyncUnaryCall <MutateRowResponse> call = client.MutateRowAsync(mutateRowRequest);
            var channelRefs = invoker.GetChannelRefsForTest();

            Assert.AreEqual(1, channelRefs.Count);
            Assert.AreEqual(1, channelRefs[0].ActiveStreamCount);

            MutateRowResponse response = call.ResponseAsync.Result;

            channelRefs = invoker.GetChannelRefsForTest();
            Assert.AreEqual(0, channelRefs[0].ActiveStreamCount);
        }
Ejemplo n.º 13
0
        public void ResultCallAsyncResponseHeaders()
        {
            var expectedMessage  = new Message <int>(10);
            var expectedHeaders  = new Metadata();
            var expectedStatus   = new Status(StatusCode.Internal, "some details");
            var expectedTrailers = new Metadata();
            var disposeCounter   = 0;

            var context = new CallContext(headers: null);

            var call = new AsyncUnaryCall <Message <int> >(
                GetAsync(expectedMessage),
                GetAsync(expectedHeaders),
                () => expectedStatus,
                () => expectedTrailers,
                () => disposeCounter++);

            using (new SynchronizationContextMock())
            {
                var result = UnaryCall <Message <int>, Message <int> > .CallAsync(call, context, CancellationToken.None).Result;

                result.ShouldBe(10);
            }

            context.ResponseHeaders.ShouldBe(expectedHeaders);
            context.ResponseTrailers.ShouldBe(expectedTrailers);
            context.ResponseStatus.ShouldBe(expectedStatus);
            disposeCounter.ShouldBe(1);
        }
Ejemplo n.º 14
0
        public void TestAsyncUnaryCallWithException()
        {
            GoogleAdsConfig config  = new GoogleAdsConfig();
            LoggingHandler  handler = new LoggingHandler(config);

            handler.WriteLogs = delegate(LogEntry logEntry)
            {
                Assert.AreEqual(config.ServerUrl, logEntry.Host);
                Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method);
                CompareMetadata(TEST_REQUEST_METADATA, logEntry.RequestHeaders);
                CompareMetadata(TEST_RESPONSE_METADATA, logEntry.ResponseHeaders);
                Assert.AreSame(TEST_REQUEST, logEntry.Request);

                // Response is null if there's an exception.
                Assert.IsNull(logEntry.Response);

                Assert.AreEqual(TEST_CUSTOMER_ID, logEntry.CustomerId);
                Assert.True(logEntry.IsFailure);
                GoogleAdsException googleAdsException = logEntry.Exception as GoogleAdsException;
                Assert.NotNull(googleAdsException);

                Assert.AreEqual(TEST_REQUEST_ID, googleAdsException.RequestId);

                Assert.NotNull(googleAdsException.Failure);
                Assert.AreEqual(1, googleAdsException.Failure.Errors.Count);
                Assert.NotNull(googleAdsException.Failure.Errors[0].ErrorCode);
                Assert.NotNull(googleAdsException.Failure.Errors[0].ErrorCode.DistinctError);
            };

            ClientInterceptorContext <HelloRequest, HelloResponse> context =
                GetClientInterceptorContext();
            AsyncUnaryCall <HelloResponse> call = ContinuationWithException(TEST_REQUEST, context);

            handler.HandleAsyncUnaryLogging(TEST_REQUEST, context, call.ResponseAsync, call);
        }
Ejemplo n.º 15
0
        public async Task SearchOpponentSucces()
        {
            //Test nie jest pełny
            int userIdFirst  = getRandomUserId();
            int userIdSecend = getRandomUserId(userIdFirst);
            int gameType     = 1; //Hmmm, skąd ma wiedzieć że to id jakiejś gry?

            //Problem
            //Co zrobić z GameData? Pomysł, ma przechowywać przebieg rozgrywki, dodatkowe dane itp. Na starcie w sumie jest puste... ale czy na pewno tak ma być?

            //Act
            AsyncUnaryCall <SearchOpponentRespons> responsAsync1 = Client.SearchOpponentAsync(new SearchOpponentRequest {
                GameType = gameType, UserId = userIdFirst
            });
            AsyncUnaryCall <SearchOpponentRespons> responsAsync2 = Client.SearchOpponentAsync(new SearchOpponentRequest {
                GameType = gameType, UserId = userIdSecend
            });

            SearchOpponentRespons respons1 = await responsAsync1;
            SearchOpponentRespons respons2 = await responsAsync2;

            //Assert
            Assert.NotNull(respons1);
            Assert.NotNull(respons2);
            Assert.AreEqual(respons1.Respons.Status, ServiceResponseStatus.Ok);
            Assert.AreEqual(respons2.Respons.Status, ServiceResponseStatus.Ok);
            Assert.NotNull(respons1.Match);
            Assert.NotNull(respons2.Match);
            Assert.IsTrue(respons1.Match.MatchUsers.Any());
            Assert.IsTrue(respons2.Match.MatchUsers.Any());
            Assert.IsTrue(respons1.Match.MatchUsers.All(al => al.User != null));
            Assert.IsTrue(respons2.Match.MatchUsers.All(al => al.User != null));
            Assert.AreEqual(respons1.Match.MatchId, respons2.Match.MatchId);
            Assert.AreEqual(respons1.Match.MatchUsers.Select(s => s.MatchUserId).ToList(), respons2.Match.MatchUsers.Select(s => s.MatchUserId).ToList());
        }
Ejemplo n.º 16
0
        async Task <TResponse> ExecAsync <TResponse>(AsyncUnaryCall <TResponse> auc, Func <AsyncUnaryCall <TResponse> > fn)
        {
            var(response, status, headers) = await GrpcUtils.GetResponseAsync(Config, auc);

            if (status?.ErrorCode != null)
            {
                var callInvoker = Config.Channel.CreateCallInvoker();
                if (await client.RetryRequest(Config, auc.GetStatus().StatusCode, status, callInvoker))
                {
                    using var retryAuc = fn();
                    var(retryResponse, retryStatus, retryHeaders) = await GrpcUtils.GetResponseAsync(Config, retryAuc);

                    if (retryStatus?.ErrorCode == null)
                    {
                        return(retryResponse);
                    }
                }

                throw new WebServiceException(status.Message)
                      {
                          StatusCode  = ResponseCallContext.GetHttpStatus(headers),
                          ResponseDto = response as object ?? new ServiceStack.EmptyResponse {
                              ResponseStatus = status
                          },
                          ResponseHeaders = GrpcUtils.ResolveHeaders(headers),
                          State           = auc.GetStatus(),
                      };
            }
            return(response);
        }
Ejemplo n.º 17
0
 public UnaryResult(Task <TResponse> rawTaskValue)
 {
     this.hasRawValue  = true;
     this.rawValueTask = new ValueTask <TResponse>(rawTaskValue);
     this.inner        = null;
     this.resolver     = null;
 }
Ejemplo n.º 18
0
        public async Task SyncDuringAsyncCallAsync()
        {
            CreateClientPipes();

            Task[] handlerTasks = CreateHandlerTasks(RespondWithMethodRequestResponse);

            const string            asyncRequest = "MyAsyncRequest";
            AsyncUnaryCall <string> asyncTask    =
                invoker.AsyncUnaryCall(stringMethod, null, new CallOptions(), asyncRequest);

            const string syncRequest  = "MySyncRequest";
            string       syncResponse =
                invoker.BlockingUnaryCall(stringMethod, null, new CallOptions(), syncRequest);

            string asyncResponse = await asyncTask;

            Assert.That(syncResponse,
                        Is.EqualTo($"{stringMethod.FullName} {syncRequest} response"));
            Assert.That(asyncResponse,
                        Is.EqualTo($"{stringMethod.FullName} {asyncRequest} response"));

            // Wait for the handlers to exit. Both should exit after the rpc they handled.
            Task.WaitAll(handlerTasks);
            Assert.That(NUM_PIPE_PAIRS, Is.EqualTo(2));
            Assert.That(handlerTasks[0].IsCompleted);
            Assert.That(handlerTasks[1].IsCompleted);

            invoker.Dispose();
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Intercepts an asynchronous invocation of a simple remote call.
        /// </summary>
        /// <param name="request">The request message of the invocation.</param>
        /// <param name="context">The <see cref="ClientInterceptorContext{TRequest, TResponse}" />
        /// associated with the current invocation.</param>
        /// <param name="continuation">The callback that continues the invocation process.
        /// This can be invoked zero or more times by the interceptor.
        /// The interceptor can invoke the continuation passing the given
        /// request value and context arguments, or substitute them as it sees fit.</param>
        /// <returns>
        /// An instance of <see cref="AsyncUnaryCall{TResponse}" />
        /// representing an asynchronous unary invocation.
        /// The interceptor can simply return the return value of the
        /// continuation delegate passed to it intact, or construct its
        /// own substitute as it sees fit.
        /// </returns>
        public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>(
            TRequest request, ClientInterceptorContext <TRequest, TResponse> context,
            AsyncUnaryCallContinuation <TRequest, TResponse> continuation)
        {
            AsyncUnaryCall <TResponse> call = continuation(request, context);

            call.ResponseAsync.ContinueWith(
                delegate(Task <TResponse> oldTask)
            {
                LogEntry logEntry = new LogEntry()
                {
                    Host            = Config.ServerUrl,
                    Method          = context.Method.FullName,
                    RequestHeaders  = context.Options.Headers,
                    Request         = request,
                    ResponseHeaders = GetResponseHeader(call),
                    Response        = (oldTask.IsFaulted) ? default(TResponse) : oldTask.Result,
                    Exception       = GetGoogleAdsException(oldTask.Exception),
                    IsFailure       = oldTask.IsFaulted,
                    CustomerId      = GetCustomerId(request)
                };
                OnLogEventAvailable?.Invoke(this, logEntry);
            });
            return(call);
        }
 public static IAsyncResponseCall <TResponse> AsResponseCall <TResponse>(this AsyncUnaryCall <TResponse> call)
 {
     if (call == null)
     {
         return(null);
     }
     return(new AsyncUnaryCallWrapper <TResponse>(call));
 }
Ejemplo n.º 21
0
 private void make_rpc <T>(AsyncUnaryCall <T> response, Action <T> handler)
 {
     Task.Run(async() =>
     {
         var result = await response;
         MainThreadEventQueue.Enqueue(() => handler(result));
     });
 }
Ejemplo n.º 22
0
        public static async Task <TResult> ToTask <TSource, TResult>(
            this AsyncUnaryCall <TSource> sourceAsync,
            Func <TSource, TResult> func)
        {
            var source = await sourceAsync.ResponseAsync;

            return(func.Invoke(source));
        }
Ejemplo n.º 23
0
        public override AsyncUnaryCall <AuthorizationResponse> LoginAsync(AuthorizationRequest request, Metadata headers = null, DateTime?deadline = null,
                                                                          CancellationToken cancellationToken            = default(CancellationToken))
        {
            AsyncUnaryCall <AuthorizationResponse> response = base.LoginAsync(request, headers, deadline, cancellationToken);

            response.ResponseAsync.ContinueWith((authResponse) => { Auth.Login(authResponse.Result.Token); });
            return(response);
        }
Ejemplo n.º 24
0
 public UnaryResponse(Task <TResponse> rawTaskValue)
 {
     this.hasRawValue  = true;
     this.rawValue     = default(TResponse);
     this.rawTaskValue = rawTaskValue;
     this.inner        = null;
     //this.resolver = null;
 }
Ejemplo n.º 25
0
        ///Sprawdza czy da się połączyć i przesłać jakie kolwiek dane
        public async Task PlayMatch()
        {
            int      userIdFirst  = getRandomUserId();
            int      userIdSecend = getRandomUserId(userIdFirst);
            int      gameType     = 1;
            GamePlay gp1          = null;
            GamePlay gp2          = null;
            AsyncDuplexStreamingCall <PlayMatchRequest, GamePlay> call = Client.PlayMatch();
            var dateStartNew = DateTime.Now.AddDays(10).ToString();
            var setDateEnd   = DateTime.Now.AddDays(20).ToShortDateString();

            //Act
            AsyncUnaryCall <SearchOpponentRespons> responsAsync1 = Client.SearchOpponentAsync(new SearchOpponentRequest {
                GameType = gameType, UserId = userIdFirst
            });
            AsyncUnaryCall <SearchOpponentRespons> responsAsync2 = Client.SearchOpponentAsync(new SearchOpponentRequest {
                GameType = gameType, UserId = userIdSecend
            });
            SearchOpponentRespons respons1 = await responsAsync1;
            SearchOpponentRespons respons2 = await responsAsync2;

            gp1 = new GamePlay {
                Match = respons1.Match
            };
            gp2 = new GamePlay {
                Match = respons2.Match
            };

            gp1.Match.DateStart = dateStartNew;
            call.RequestStream.WriteAsync(new PlayMatchRequest {
                GamePlay = gp1, UserId = userIdFirst
            });                                                                                           //Wywołuje ruch
            while (await call.ResponseStream.MoveNext(CancellationToken.None))
            {
                gp2 = call.ResponseStream.Current;
                break;
            }

            gp2.Match.DateEnd = setDateEnd;
            call.RequestStream.WriteAsync(new PlayMatchRequest {
                GamePlay = gp2, UserId = userIdSecend
            });                                                                                           //Wywołuje ruch
            while (await call.ResponseStream.MoveNext(CancellationToken.None))
            {
                gp1 = call.ResponseStream.Current;
                break;
            }

            //Asert
            Assert.NotNull(gp1);
            Assert.NotNull(gp2);
            Assert.NotNull(gp1.Match);
            Assert.NotNull(gp2.Match);
            Assert.AreEqual(gp2.Match.DateStart, dateStartNew);
            Assert.AreEqual(gp1.Match.DateStart, dateStartNew);
            Assert.AreEqual(gp2.Match.DateEnd, setDateEnd);
            Assert.AreEqual(gp1.Match.DateEnd, setDateEnd);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// 异步简单调用
        /// </summary>
        /// <typeparam name="TRequest"></typeparam>
        /// <typeparam name="TResponse"></typeparam>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <param name="continuation"></param>
        /// <returns></returns>
        public override AsyncUnaryCall <TResponse> AsyncUnaryCall <TRequest, TResponse>(TRequest request, ClientInterceptorContext <TRequest, TResponse> context, AsyncUnaryCallContinuation <TRequest, TResponse> continuation)
        {
            Console.WriteLine("客户端调用执行开始");
            var responseCon = continuation(request, context);
            var response    = new AsyncUnaryCall <TResponse>(responseCon.ResponseAsync, responseCon.ResponseHeadersAsync, responseCon.GetStatus, responseCon.GetTrailers, responseCon.Dispose);

            Console.WriteLine("客户端调用执行结束");
            return(response);
        }
 /// <summary>
 /// Intercepts an async unary call adds a custom exception handler.
 /// </summary>
 /// <typeparam name="TResponse">The type of the response.</typeparam>
 /// <param name="call">The async unary call to intercept.</param>
 /// <returns>The async unary call with custom exception handling for
 /// <see cref="RpcException"/>.</returns>
 internal static AsyncUnaryCall <TResponse> Intercept <TResponse>(AsyncUnaryCall <TResponse> call)
 {
     return(new AsyncUnaryCall <TResponse>(
                Intercept <TResponse, TResponse>(call.ResponseAsync),
                Intercept <Metadata, TResponse>(call.ResponseHeadersAsync),
                Intercept <Status, TResponse>(call.GetStatus),
                Intercept <Metadata, TResponse>(call.GetTrailers),
                Intercept <TResponse>(call.Dispose)));
 }
Ejemplo n.º 28
0
        public static void Main(string[] args)
        {
            //建立通道
            Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);

            //新建客户端
            var client = new SurvCenterService.SurvCenterServiceClient(channel);
            //任意设置一些属性值
            String user = "******";
            //新建报警事件
            Event nevent = new Event();

            nevent.Description = user;
            //新建报警事件图片
            AnnotatedImage anno_img = new AnnotatedImage();

            //将二进制JPEG码流拷贝到报警事件图片中
            anno_img.Img = Google.Protobuf.ByteString.CopyFrom(new byte[] { 1, 2 });
            //设置报警事件图片中的目标
            Target target = new Target {
                X = 1, Y = 2, W = 3, H = 4, Type = Target.Types.Type.Person
            };

            anno_img.Targets.Add(target);
            nevent.AnnoImgs.Add(anno_img);

            //向服务器提交报警事件
            System.Collections.Generic.List <AsyncUnaryCall <GeneralReply> > rets = new System.Collections.Generic.List <AsyncUnaryCall <GeneralReply> >();
            for (int i = 0; i < 1000; i++)
            {
                AsyncUnaryCall <GeneralReply> ret = client.ReportEventAsync(nevent);
                rets.Add(ret);
            }
            Console.WriteLine("number: ", rets.Count);
            for (int i = 0; i < rets.Count; ++i)
            {
                rets[i].ResponseAsync.Wait();
                Console.WriteLine("reportevent: " + rets[i].ResponseAsync.Result);
            }
            //Console.WriteLine("Greeting: " + reply.Message);

            HeartbeatRequest hr = new HeartbeatRequest();

            hr.DeviceAddress = "127.0.0.1";
            hr.DeviceIdent   = "i am a deivce";
            //异步调用心跳请求
            var hr_reply = client.HeartbeatAsync(hr);

            //等待异步操作返回,具体实现时可以使用完整异步机制
            hr_reply.ResponseAsync.Wait();
            Console.WriteLine("Heartbeat over: " + hr_reply.ResponseAsync.Result);

            channel.ShutdownAsync().Wait();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
        private AsyncUnaryCall <SearchResponse> ValueFunction()
        {
            var response = new AsyncUnaryCall <SearchResponse>(
                FakeResponse(),
                Task.FromResult(default(Metadata)),
                () => Status.DefaultSuccess,
                () => Metadata.Empty,
                delegate { });

            return(response);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Invokes a Bond nothing method.
        /// </summary>
        /// <remarks>
        /// The result--whether successful or unsuccessful--of a nothing method cannot be observed.
        /// This method invokes the call and sets up the gRPC response to be ignored.
        /// </remarks>
        /// <typeparam name="TRequest">The type of the request</typeparam>
        /// <param name="callInvoker">A client call invoker</param>
        /// <param name="method">The method to invoke</param>
        /// <param name="host">The host</param>
        /// <param name="options">The call options</param>
        /// <param name="request">The request object</param>
        public static void NothingCall <TRequest>(
            CallInvoker callInvoker,
            Method <TRequest, IMessage <Bond.Void> > method,
            string host,
            CallOptions options,
            TRequest request)
            where TRequest : class
        {
            AsyncUnaryCall <IMessage <Bond.Void> > call = callInvoker.AsyncUnaryCall(method, host, options, request);

            call.ResponseAsync.ContinueWith(ObserveAndIgnoreTaskException, TaskContinuationOptions.OnlyOnFaulted);
        }