public override async Task StreamingCall(IAsyncStreamReader<SimpleRequest> requestStream, IServerStreamWriter<SimpleResponse> responseStream, ServerCallContext context)
 {
     await requestStream.ForEachAsync(async request =>
     {
         var response = new SimpleResponse { Payload = CreateZerosPayload(request.ResponseSize) };
         await responseStream.WriteAsync(response);
     });
 }
 public Task ListenForNewPeople(ListenForNewPeopleRequest request, IServerStreamWriter<Person> responseStream, ServerCallContext context)
 {
     LogRpc(context);
     _personRepository.PersonCreated += async (sender, arg) => await responseStream.WriteAsync(arg.Person);
     _manualResetEvent.Wait();
     return Task.FromResult(0);
 }
Beispiel #3
1
 public async Task DivMany(ServerCallContext context, IAsyncStreamReader<DivArgs> requestStream, IServerStreamWriter<DivReply> responseStream)
 {
     await requestStream.ForEach(async divArgs =>
     {
         await responseStream.WriteAsync(DivInternal(divArgs));
     });
 }
Beispiel #4
0
        public override Task <Empty> Setup(SetupRequest request, Grpc.Core.ServerCallContext context)
        {
            var payments = request.Payments.Select(p => mapper.Map <Repository.Payment>(p));

            paymentsRepository.Setup(payments);
            return(Task.FromResult(new Empty()));
        }
        public override async Task RequestFrameStream(
            Grpc.Core.IAsyncStreamReader <CameraAcquisitionRequest> requestStream,
            Grpc.Core.IServerStreamWriter <BufferedFramesResponse> responseStream, Grpc.Core.ServerCallContext context)
        {
            lock (_frameStreamWriterLock)
            {
                _frameStreamWriter = responseStream;
            }

            while (await requestStream.MoveNext() && !context.CancellationToken.IsCancellationRequested)
            {
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                var result = await RequestCameraAcquisition(requestStream.Current, context);

                if (result.Error != null)
                {
                    lock (_frameStreamWriterLock)
                    {
                        responseStream.WriteAsync(new BufferedFramesResponse()
                        {
                            Error = result.Error
                        });
                        break;
                    }
                }
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }

            lock (_frameStreamWriterLock)
            {
                _frameStreamWriter = null;
            }
        }
        public override Task <BufferedFramesResponse> RequestBufferedFrames(BufferedFramesRequest request,
                                                                            Grpc.Core.ServerCallContext context)
        {
            var ret = new BufferedFramesResponse();

            try
            {
                foreach (var frame in _frames)
                {
                    if (frame.ReceiveStatus == VmbFrameStatusType.VmbFrameStatusComplete)
                    {
                        var output = MakeImageBuffer(new FrameData(frame));
                        var bs     = ByteString.FromStream(output);

                        ret.Images.Add(bs);
                    }
                }
            }
            catch (Exception e)
            {
                ret.Error = ServiceHelper.BuildError(e, Error.Types.Level.Error);
            }

            return(Task.FromResult(ret));
        }
 public async Task OperationStream(IAsyncStreamReader<ServiceRequest> requestStream, IServerStreamWriter<ServiceResponse> responseStream, ServerCallContext context)
 {
     while (await requestStream.MoveNext(CancellationToken.None))
     {
         await responseStream.WriteAsync(new ServiceResponse { Id = requestStream.Current.Id });
     }
 }
Beispiel #8
0
        public override Task <BranchGroupDTO> GetBranchGroup(KeyObject request, Grpc.Core.ServerCallContext context)
        {
            int id          = Convert.ToInt32(request.Body);
            var branchGroup = _branchGroupDao.Get(id);

            return(Task.FromResult(_mapper.Map <BranchGroupDTO>(branchGroup)));
        }
Beispiel #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GrpcService"/> class.
 /// </summary>
 /// <param name="context">The <see cref="grpc.ServerCallContext"/>.</param>
 /// <param name="func">The function to invoke.</param>
 /// <param name="operationType">The <see cref="Beef.OperationType"/>.</param>
 /// <param name="statusCode">The <see cref="HttpStatusCode"/>.</param>
 /// <param name="memberName">The method or property name of the caller to the method.</param>
 /// <param name="filePath">The full path of the source file that contains the caller.</param>
 /// <param name="lineNumber">The line number in the source file at which the method is called.</param>
 public GrpcService(grpc.ServerCallContext context, Func <Task> func, OperationType operationType = OperationType.Unspecified,
                    HttpStatusCode statusCode            = HttpStatusCode.NoContent,
                    [CallerMemberName] string?memberName = null, [CallerFilePath] string?filePath = null, [CallerLineNumber] int lineNumber = 0)
     : base(context, operationType, statusCode, statusCode, memberName, filePath, lineNumber)
 {
     _func = func ?? throw new ArgumentNullException(nameof(func));
 }
        /// <summary>
        /// Gets a stream of points, and responds with statistics about the "trip": number of points,
        /// number of known features visited, total distance traveled, and total time spent.
        /// </summary>
        public override async Task<RouteSummary> RecordRoute(IAsyncStreamReader<Point> requestStream, ServerCallContext context)
        {
            int pointCount = 0;
            int featureCount = 0;
            int distance = 0;
            Point previous = null;
            var stopwatch = new Stopwatch();
            stopwatch.Start();

            while (await requestStream.MoveNext())
            {
                var point = requestStream.Current;
                pointCount++;
                if (CheckFeature(point).Exists())
                {
                    featureCount++;
                }
                if (previous != null)
                {
                    distance += (int) previous.GetDistance(point);
                }
                previous = point;
            }

            stopwatch.Stop();
            
            return new RouteSummary
            {
                PointCount = pointCount,
                FeatureCount = featureCount,
                Distance = distance,
                ElapsedTime = (int)(stopwatch.ElapsedMilliseconds / 1000)
            };
        }
Beispiel #11
0
        public override Task <BlogResponse> UpdateBlogUnary(BlogRequest request, Grpc.Core.ServerCallContext context)
        {
            Console.WriteLine("Server received a normal blog request. Server will response normally!!!");
            var filter = new FilterDefinitionBuilder <BsonDocument>().Eq("_id", new ObjectId(request.Blog.Id));
            var result = _mongoCollection.Find(filter).FirstOrDefault();

            if (result == null)
            {
                throw new RpcException(new Status(StatusCode.NotFound, String.Format("Blog Id {0} not found", request.Blog.Id)));
            }

            Blog         blog = request.Blog;
            BsonDocument doc  = new BsonDocument();

            doc.Add("author_id", blog.AuthorId);
            doc.Add("title", blog.Title);
            doc.Add("content", blog.Content);

            _mongoCollection.ReplaceOne(filter, doc);

            return(Task.FromResult(new BlogResponse()
            {
                Blog = blog
            }));
        }
Beispiel #12
0
        public override async Task LoadSitesList(SettingsRequest request,
                                                 Grpc.Core.IServerStreamWriter <Settings> responseStream,
                                                 Grpc.Core.ServerCallContext context)
        {
            List <Settings> responses = null;

            string        userid   = request.Userid;
            List <String> settings = db.GetUserSettings(userid, "site");

            foreach (var setting in settings)
            {
                await responseStream.WriteAsync(new Settings { Userid = userid, Field = setting });
            }
            Console.WriteLine("\nSettings sent to client. Userid: " + userid);

            //responses.Add();
            //лямбдой
            //responses = db.GetUserSettings(userid, "site").Cast<List<Settings>>(){ new Settings { }};
            //settings.FindAll((feature) => feature.Exists() && request.Contains(feature.Location));
            //получаем из бд настройки для конкретного пользователя
            //foreach (var response in responses)
            //{
            //    await responseStream.WriteAsync(response);
            //}
        }
        public async override Task <Empty> AddItem(AddItemRequest request, Grpc.Core.ServerCallContext context)
        {
            using var parent = ActivitySource.StartActivity("hipstershop.CartService/AddItem", ActivityKind.Server);
            await cartStore.AddItemAsync(request.UserId, request.Item.ProductId, request.Item.Quantity);

            return(Empty);
        }
        public static bool Validate(ServerCallContext context)
        {
            Metadata.Entry metadataEntry = context.RequestHeaders.FirstOrDefault(m =>
                String.Equals(m.Key, ActiveDirectoryCredentialsFactory.AuthorizationHeader, StringComparison.Ordinal));

            if (metadataEntry.Equals(default(Metadata.Entry)) || metadataEntry.Value == null)
            {
                return false;
            }

            string authorizationHeaderValue = Encoding.UTF8.GetString(Convert.FromBase64String(metadataEntry.Value));
            if (String.IsNullOrWhiteSpace(authorizationHeaderValue))
            {
                return false;
            }

            var splitedString = authorizationHeaderValue.Split(':');
            if (splitedString.Length < 3)
            {
                return false;
            }

            string userName = splitedString[0];
            string password = splitedString[1];
            string domain = splitedString[2];

            return ValidateLdapCredentials(userName, password, domain);
        }
        public override async Task getAllCustomer(Empty request,
                                                  Grpc.Core.IServerStreamWriter <Customer> responseStream,
                                                  Grpc.Core.ServerCallContext context)
        {
            List <Customer> responses = new List <Customer>();

            try
            {
                conPG.Open();
                strQuery = "SELECT * FROM handson_user";
                NpgsqlCommand    command = ExecutePGQuery(strQuery);
                NpgsqlDataReader dtr     = command.ExecuteReader();
                while (dtr.Read())
                {
                    Customer cus = new Customer();
                    cus.Id       = Convert.ToString(dtr["id"]);
                    cus.Username = Convert.ToString(dtr["username"]);
                    cus.Password = Convert.ToString(dtr["password"]);

                    responses.Add(cus);
                }
            }
            catch (Exception)
            {
                throw;
            }
            foreach (var response in responses)
            {
                await responseStream.WriteAsync(response);
            }
        }
Beispiel #16
0
        public override Task <CarReply> GetCar(CarRequest request, Grpc.Core.ServerCallContext context)
        {
            var r = new CarReply();
            var f = r.Documents;

            return(base.GetCar(request, context));
        }
 /// <summary>
 /// Gets all features contained within the given bounding rectangle.
 /// </summary>
 public override async Task ListFeatures(Rectangle request, IServerStreamWriter<Feature> responseStream, ServerCallContext context)
 {
     var responses = features.FindAll( (feature) => feature.Exists() && request.Contains(feature.Location) );
     foreach (var response in responses)
     {
         await responseStream.WriteAsync(response);
     }
 }
        public override async Task<SimpleResponse> UnaryCall(SimpleRequest request, ServerCallContext context)
        {
            await EnsureEchoMetadataAsync(context);
            EnsureEchoStatus(request.ResponseStatus, context);

            var response = new SimpleResponse { Payload = CreateZerosPayload(request.ResponseSize) };
            return response;
        }
Beispiel #19
0
 public override Task <Workout> StartWorkout(Empty empty, Grpc.Core.ServerCallContext context)
 {
     return(Task.FromResult(new Workout {
         Who = new User {
             Username = "******"
         }, State = WorkoutState.Start
     }));
 }
Beispiel #20
0
 public override async Task ServerReflectionInfo(IAsyncStreamReader<ServerReflectionRequest> requestStream, IServerStreamWriter<ServerReflectionResponse> responseStream, ServerCallContext context)
 {
     while (await requestStream.MoveNext())
     {
         var response = ProcessRequest(requestStream.Current);
         await responseStream.WriteAsync(response);
     }
 }
        public override async Task AnalyzerRegistration(RegisterToRecieveHandlerMessages msg,
                                                        Grpc.Core.IServerStreamWriter <NewImageRequest> responseStream,
                                                        Grpc.Core.ServerCallContext context)
        {
            await MailBag.Get().AnalyzerMessageLoop(responseStream);

            await Task.Delay(-1);
        }
Beispiel #22
0
 public async Task StreamingOutputCall(StreamingOutputCallRequest request, IServerStreamWriter<StreamingOutputCallResponse> responseStream, ServerCallContext context)
 {
     foreach (var responseParam in request.ResponseParameters)
     {
         var response = new StreamingOutputCallResponse { Payload = CreateZerosPayload(responseParam.Size) };
         await responseStream.WriteAsync(response);
     }
 }
 public override async Task<Num> Sum(IAsyncStreamReader<Num> requestStream, ServerCallContext context)
 {
     long sum = 0;
     await requestStream.ForEachAsync(async num =>
     {
         sum += num.Num_;
     });
     return new Num { Num_ = sum };
 }
Beispiel #24
0
 public async Task<Num> Sum(ServerCallContext context, IAsyncStreamReader<Num> requestStream)
 {
     long sum = 0;
     await requestStream.ForEach(async num =>
     {
         sum += num.Num_;
     });
     return Num.CreateBuilder().SetNum_(sum).Build();
 }
 public async Task<StreamingInputCallResponse> StreamingInputCall(IAsyncStreamReader<StreamingInputCallRequest> requestStream, ServerCallContext context)
 {
     int sum = 0;
     await requestStream.ForEachAsync(async request =>
     {
         sum += request.Payload.Body.Length;
     });
     return StreamingInputCallResponse.CreateBuilder().SetAggregatedPayloadSize(sum).Build();
 }
        public async override Task <Empty> AddItem(AddItemRequest request, Grpc.Core.ServerCallContext context)
        {
            using (GlobalTracer.Instance.BuildSpan("AddItem").StartActive())
            {
                await cartStore.AddItemAsync(request.UserId, request.Item.ProductId, request.Item.Quantity);

                return(Empty);
            }
        }
Beispiel #27
0
 public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
 {
     Console.WriteLine($"{context.Method}:{context.Peer} time:{Utils.GetTimeNow()}");
     foreach (var header in context.RequestHeaders)
     {
         Console.WriteLine($"{header.Key}:{header.Value}");
     }
     return Task.FromResult(new HelloReply { Message = "holle " + request.Name });
 }
Beispiel #28
0
 public async Task<StreamingInputCallResponse> StreamingInputCall(IAsyncStreamReader<StreamingInputCallRequest> requestStream, ServerCallContext context)
 {
     int sum = 0;
     await requestStream.ForEachAsync(async request =>
     {
         sum += request.Payload.Body.Length;
     });
     return new StreamingInputCallResponse { AggregatedPayloadSize = sum };
 }
 public async Task StreamingOutputCall(StreamingOutputCallRequest request, IServerStreamWriter<StreamingOutputCallResponse> responseStream, ServerCallContext context)
 {
     foreach (var responseParam in request.ResponseParametersList)
     {
         var response = StreamingOutputCallResponse.CreateBuilder()
             .SetPayload(CreateZerosPayload(responseParam.Size)).Build();
         await responseStream.WriteAsync(response);
     }
 }
Beispiel #30
0
        public override Task <Empty> SetupAppend(SetupRequest request, Grpc.Core.ServerCallContext context)
        {
            var payments = request.Payments.Select(p => mapper.Map <Models.Payment>(p));

            paymentsRepository.SetupAppend(payments);
            projectionChannel.Publish(null, new DataProjection <Models.Payment, string> {
                Upsert = payments.ToArray()
            });
            return(Task.FromResult(new Empty()));
        }
 public async Task<PersonListResponse> CreatePeople(IAsyncStreamReader<Person> requestStream, ServerCallContext context)
 {
     LogRpc(context);
     while (await requestStream.MoveNext(CancellationToken.None))
     {
         var person = requestStream.Current;
         _personRepository.TryCreate(person);
     }
     return new PersonListResponse { People = { _personRepository.GetAllPeople() } };
 }
Beispiel #32
0
 public async Task FullDuplexCall(IAsyncStreamReader<StreamingOutputCallRequest> requestStream, IServerStreamWriter<StreamingOutputCallResponse> responseStream, ServerCallContext context)
 {
     await requestStream.ForEachAsync(async request =>
     {
         foreach (var responseParam in request.ResponseParameters)
         {
             var response = new StreamingOutputCallResponse { Payload = CreateZerosPayload(responseParam.Size) };
             await responseStream.WriteAsync(response);
         }
     });
 }
        public async override Task <Empty> AddItem(AddItemRequest request, Grpc.Core.ServerCallContext context)
        {
            using (var activity = TraceActivitySource.StartActivity("AddItem", ActivityKind.Server, this.traceContextFromGrpcContext(context)))
            {
                activity?.SetTag("component", "rpc");
                activity?.SetTag("grpc.method", "/hipstershop.CartService/AddItem");
                await cartStore.AddItemAsync(request.UserId, request.Item.ProductId, request.Item.Quantity);

                return(Empty);
            }
        }
        public override async Task StreamingOutputCall(StreamingOutputCallRequest request, IServerStreamWriter<StreamingOutputCallResponse> responseStream, ServerCallContext context)
        {
            await EnsureEchoMetadataAsync(context);
            EnsureEchoStatus(request.ResponseStatus, context);

            foreach (var responseParam in request.ResponseParameters)
            {
                var response = new StreamingOutputCallResponse { Payload = CreateZerosPayload(responseParam.Size) };
                await responseStream.WriteAsync(response);
            }
        }
Beispiel #35
0
 public async Task FullDuplexCall(ServerCallContext context, IAsyncStreamReader<StreamingOutputCallRequest> requestStream, IServerStreamWriter<StreamingOutputCallResponse> responseStream)
 {
     await requestStream.ForEach(async request =>
     {
         foreach (var responseParam in request.ResponseParametersList)
         {
             var response = StreamingOutputCallResponse.CreateBuilder()
                 .SetPayload(CreateZerosPayload(responseParam.Size)).Build();
             await responseStream.WriteAsync(response);
         }
     });
 }
Beispiel #36
0
        public async override Task <Empty> AddItem(AddItemRequest request, Grpc.Core.ServerCallContext context)
        {
            DistributedTracingData distributedTracingData = getDistributedTracingData(context);
            await Agent.Tracer.CaptureTransaction("AddItem", ApiConstants.TypeRequest, async (t) => {
                t.Labels["userId"]    = request.UserId;
                t.Labels["productId"] = request.Item.ProductId;
                t.Labels["quantity"]  = request.Item.Quantity.ToString();
                await cartStore.AddItemAsync(request.UserId, request.Item.ProductId, request.Item.Quantity);
            }, distributedTracingData);

            return(Empty);
        }
Beispiel #37
0
        public override Task <Todos> List(Empty request, Grpc.Core.ServerCallContext context)
        {
            Logger.LogInformation("calling rpc service operation 'List'");
            var response = new Todos();

            lock (this.mylock)
            {
                response.Todos_.Add(this.todos.Select(p => p.Value).ToArray());
            }

            return(Task.FromResult(response));
        }
        public override async Task Fib(FibArgs request, IServerStreamWriter<Num> responseStream, ServerCallContext context)
        {
            var limit = request.Limit > 0 ? request.Limit : long.MaxValue;
            var fibEnumerator = FibInternal(limit).GetEnumerator();

            // Keep streaming the sequence until the call is cancelled.
            // Use CancellationToken from ServerCallContext to detect the cancellation.
            while (!context.CancellationToken.IsCancellationRequested && fibEnumerator.MoveNext())
            {
                await responseStream.WriteAsync(fibEnumerator.Current);
                await Task.Delay(100);
            }
        }
 public async Task<ChatMessageCollection> GetChatHistory(IAsyncStreamReader<ChatMessageRequest> requestStream, ServerCallContext context)
 {
     Log(context);
     var responses = new List<ChatMessage>();
     // Async enumerator
     while (await requestStream.MoveNext(CancellationToken.None))
     {
         ChatMessageRequest chatMessageRequest = requestStream.Current;
         ICollection<ChatMessage> chatMessages = await _chatMessageRepository.GetAccountChatHistoryAsync(chatMessageRequest.AccountId);
         responses.AddRange(chatMessages);
     }
     return new ChatMessageCollection { ChatMessages = { responses } };
 }
Beispiel #40
0
        public override Task <BooleanObject> DeleteBranchGroup(KeyObject request, Grpc.Core.ServerCallContext context)
        {
            var branchGroup = new BranchGroup()
            {
                Id = Convert.ToInt32(request.Body)
            };
            var success = _branchGroupDao.Delete(branchGroup);

            return(Task.FromResult(new BooleanObject()
            {
                Body = success
            }));
        }
Beispiel #41
0
        public async override Task <InvokeResponse> OnInvoke(InvokeRequest request, Grpc.Core.ServerCallContext context)
        {
            if (!WorkflowExists(request.Method))
            {
                throw new RpcException(new Status(StatusCode.InvalidArgument, $"Worflow with name {request.Method} was not found"));
            }
            var resp = await ExecuteWorkflow(request.Method);

            return(new InvokeResponse()
            {
                Data = resp,
            });
        }
        public async override Task <Empty> AddItem(AddItemRequest request, Grpc.Core.ServerCallContext context)
        {
            IIncomingRemoteCallTracer incomingRemoteCallTracer = getTracer(context, "AddItem");

            try {
                await incomingRemoteCallTracer.TraceAsync(() => cartStore.AddItemAsync(request.UserId, request.Item.ProductId, request.Item.Quantity));
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
                incomingRemoteCallTracer.Error(e);
            } finally {
                incomingRemoteCallTracer.End();
            }

            return(Empty);
        }
Beispiel #43
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GrpcServiceBase"/> class.
        /// </summary>
        /// <param name="context">The underlying <see cref="grpc.ServerCallContext"/>.</param>
        /// <param name="operationType">The <see cref="Beef.OperationType"/>.</param>
        /// <param name="statusCode">The primary <see cref="HttpStatusCode"/>.</param>
        /// <param name="alternateStatusCode">The alternate <see cref="HttpStatusCode"/> (where supported; i.e. not <c>null</c>).</param>
        /// <param name="memberName">The method or property name of the caller.</param>
        /// <param name="filePath">The full path of the source file that contains the caller.</param>
        /// <param name="lineNumber">The line number in the source file at which the method is called.</param>
        protected GrpcServiceBase(grpc.ServerCallContext context, OperationType operationType,
                                  HttpStatusCode statusCode, HttpStatusCode?alternateStatusCode = null,
                                  [CallerMemberName] string?memberName = null, [CallerFilePath] string?filePath = null, [CallerLineNumber] int lineNumber = 0)
        {
            Context             = context ?? throw new ArgumentNullException(nameof(context));
            OperationType       = operationType;
            StatusCode          = statusCode;
            AlternateStatusCode = alternateStatusCode;
            CallerMemberName    = memberName !;
            CallerFilePath      = filePath !;
            CallerLineNumber    = lineNumber;

            // Add to the ExecutionContext in case we need access to the originating request at any stage.
            ExecutionContext.Current.Properties.Add(ExecutionContextPropertyKey, this);
        }
Beispiel #44
0
        public override async Task <Empty> UpdateSession(SessionRequest request, Grpc.Core.ServerCallContext context)
        {
            var sessionModel = MapToSessionModel(request);

            var response = await _repository.UpdateSessionAsync(sessionModel);

            if (response != null)
            {
                return(new Empty());
            }

            context.Status = new Status(StatusCode.NotFound, $"Session {request.AuthType.ToString()}_{request.ChatId.ToString()} does not exist");

            return(new Empty());
        }
Beispiel #45
0
        public Task<HealthCheckResponse> Check(HealthCheckRequest request, ServerCallContext context)
        {
            lock (myLock)
            {
                var host = request.HasHost ? request.Host : "";
                var service = request.HasService ? request.Service : "";

                HealthCheckResponse.Types.ServingStatus status;
                if (!statusMap.TryGetValue(CreateKey(host, service), out status))
                {
                    // TODO(jtattermusch): returning specific status from server handler is not supported yet.
                    throw new RpcException(new Status(StatusCode.NotFound, ""));
                }
                return Task.FromResult(HealthCheckResponse.CreateBuilder().SetStatus(status).Build());
            }
        }
Beispiel #46
0
        public override Task <Empty> Delete(DeleteRequest request, Grpc.Core.ServerCallContext context)
        {
            if (request.Id == 0)
            {
                Logger.LogWarning("can not delete a todo with id {ID}", request.Id);
                throw new RpcException(new Status(StatusCode.InvalidArgument
                                                  , $"can not delete a todo with id {request.Id}"));
            }

            lock (this.mylock)
            {
                this.todos.Remove(request.Id);
            }

            return(Task.FromResult(new Empty()));
        }
Beispiel #47
0
        public override Task <Empty> Shutdown(Empty request, Core.ServerCallContext context)
        {
            lock (_shutdownTcs)
            {
                if (_shutdownRequested)
                {
                    throw new InvalidOperationException("Service shutdown already requested");
                }

                _shutdownRequested = true;
            }

            _shutdownTcs.SetResult(null);

            return(Task.FromResult(new Empty()));
        }
Beispiel #48
0
        public async Task Fib(ServerCallContext context, FibArgs request, IServerStreamWriter<Num> responseStream)
        {
            if (request.Limit <= 0)
            {
                // TODO(jtattermusch): support cancellation
                throw new NotImplementedException("Not implemented yet");
            }

            if (request.Limit > 0)
            {
                foreach (var num in FibInternal(request.Limit))
                {
                    await responseStream.WriteAsync(num);
                }
            }
        }
        public async Task Chat(IAsyncStreamReader<ChatMessage> requestStream, IServerStreamWriter<ChatMessage> responseStream, ServerCallContext context)
        {
            Log(context);

            Program.Log("Server starting to chat");
            while (await requestStream.MoveNext())
            {
                ChatMessage clientChatMessage = requestStream.Current;
                Program.Log($"Client says {clientChatMessage}");

                ChatMessage serverChatMessage = Utility.GetRandomChatMessage(0);
                await responseStream.WriteAsync(serverChatMessage);
            }

            // Returning from the method will automatically complete the response async enumerator on the client.
        }
Beispiel #50
0
        public override async Task <Movies> GetMovieByName(NameMovie request, Grpc.Core.ServerCallContext context)
        {
            try
            {
                var httpContext       = context.GetHttpContext();
                var clientCertificate = httpContext.Connection.ClientCertificate;

                string url      = "https://jsonmock.hackerrank.com/api/movies/search/?Title=" + request.Name;
                var    response = await client.GetStringAsync(url);

                MoviesPage moviesPage = JsonConvert.DeserializeObject <MoviesPage>(response);

                //Verificar de precisa inicializar.
                Movies movies = new Movies();
                movies.Total = moviesPage.Total;

                //Run the next iteration, because the first was executed
                for (int i = 2; i <= moviesPage.Total_pages; i++)
                {
                    List <MovieData> movieData = new List <MovieData>();
                    movieData = await GetMoviebyNameAndPage(request.Name, i.ToString());

                    moviesPage.Data.AddRange(movieData);
                }

                foreach (var line in moviesPage.Data.GroupBy(movie => movie.Year)
                         .Select(group => new {
                    Year = group.Key,
                    Count = group.Count()
                })
                         .OrderBy(x => x.Year))
                {
                    MoviesByYear moviesByYear = new MoviesByYear();
                    moviesByYear.Year   = line.Year;
                    moviesByYear.Movies = line.Count;
                    movies.MoviesByYear.Add(moviesByYear);
                }

                return(movies);
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao pesquisar o filme " + request.Name + "."
                                    + "Excessão: " + ex.Message);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task <CameraParametersResponse> RequestCameraParameters(CameraParametersRequest request,
                                                                                Grpc.Core.ServerCallContext context)
        {
            var ret = new CameraParametersResponse();

            if (request.Write)
            {
                try
                {
                    // configure camera parameters
                    var features = _cameraInstance.Features;
                    features["ExposureTime"].FloatValue         = request.Params.ExposureTime;
                    features["AcquisitionFrameRate"].FloatValue = request.Params.FrameRate;
                    features["Gain"].FloatValue = request.Params.Gain;
                    features["AcquisitionFrameCount"].IntValue = _numFrames = request.Params.NumFrames;
                }
                catch (Exception e)
                {
                    ret.Error = ServiceHelper.BuildError(e, Error.Types.Level.Error);
                    return(Task.FromResult(ret));
                }
            }
            else
            {
                // read parameters
                try
                {
                    var features = _cameraInstance.Features;
                    ret.Params = new CameraParameters()
                    {
                        ExposureTime = features["ExposureTime"].FloatValue,
                        FrameRate    = features["AcquisitionFrameRate"].FloatValue,
                        Gain         = features["Gain"].FloatValue,
                        NumFrames    = _numFrames
                    };
                }
                catch (Exception e)
                {
                    ret.Error = ServiceHelper.BuildError(e, Error.Types.Level.Error);
                    return(Task.FromResult(ret));
                }
            }

            return(Task.FromResult(ret));
        }
Beispiel #52
0
        public override Task <Todo> Create(Todo request, Grpc.Core.ServerCallContext context)
        {
            if (request.Id != 0 || string.IsNullOrEmpty(request.Text))
            {
                Logger.LogWarning("invalid todo received {@Todo}", request);
                throw new RpcException(new Status(StatusCode.InvalidArgument
                                                  , request.Id != 0 ? "id must not be set" : "a todo needs a title"));
            }

            lock (this.mylock)
            {
                request.Id = this.id++;
                this.todos.Add(request.Id, request);
            }

            Logger.LogInformation("todo successfully created {@Todo}", request);
            return(Task.FromResult(request));
        }
        public async Task ListenChat(ChatMessageRequest request, IServerStreamWriter<ChatMessage> responseStream, ServerCallContext context)
        {
            Log(context);
            using (IAsyncEnumerator<ChatMessage> enumerator = _chatMessageRepository.ListenAccountChatAsync(request.AccountId).GetEnumerator())
            {
                // Custom reponse header
                await context.WriteResponseHeadersAsync(new Metadata { new Metadata.Entry("Some-response-header-key", "Some-response-header-value") });

                // Async enumerator
                while (await enumerator.MoveNext())
                {
                    ChatMessage chatMessage = enumerator.Current;
                    await responseStream.WriteAsync(chatMessage);
                }

                // Custom response trailer
                context.ResponseTrailers.Add(new Metadata.Entry("Some-response-tailer-key", "Some-response-trailer-value"));
            }
        }
Beispiel #54
0
        public override Task <PlayerReply> GetPlayer(PlayerRequest request, Grpc.Core.ServerCallContext context)
        {
            _logger.LogInformation("Querying for player...");

            var Player = _Db.GetPlayers()
                         .Where(candidate => String.Equals(candidate.Name, request.Name, StringComparison.OrdinalIgnoreCase))
                         .FirstOrDefault();

            var wrapReply = new PlayerReply {
                Message = $"Could not find Player {request.Name}"
            };

            if (Player != null)
            {
                wrapReply = new PlayerReply {
                    Message = $"Found {request.Name}",
                    Player  = Player
                };
            }
            return(Task.FromResult(wrapReply));
        }
Beispiel #55
0
        public override Task <Todo> Update(Todo request, Grpc.Core.ServerCallContext context)
        {
            if (request.Id == 0 || string.IsNullOrEmpty(request.Text))
            {
                Logger.LogWarning("invalid todo received {@Todo}", request);
                throw new RpcException(new Status(StatusCode.InvalidArgument
                                                  , request.Id == 0 ? "id must be set" : "a todo needs a title"));
            }

            lock (this.mylock)
            {
                if (!this.todos.ContainsKey(request.Id))
                {
                    Logger.LogWarning("id {ID} not found", request.Id);
                    throw new RpcException(new Status(StatusCode.NotFound, $"id {request.Id} not found"));
                }
                this.todos[request.Id] = request;
            }
            Logger.LogInformation("todo successfully updated {@Todo}", request);
            return(Task.FromResult(request));
        }
        public override async Task RunClient(IAsyncStreamReader<ClientArgs> requestStream, IServerStreamWriter<ClientStatus> responseStream, ServerCallContext context)
        {
            GrpcPreconditions.CheckState(await requestStream.MoveNext());
            var clientConfig = requestStream.Current.Setup;
            var runner = ClientRunners.CreateStarted(clientConfig);

            await responseStream.WriteAsync(new ClientStatus
            {
                Stats = runner.GetStats(false)
            });

            while (await requestStream.MoveNext())
            {
                var reset = requestStream.Current.Mark.Reset;
                await responseStream.WriteAsync(new ClientStatus
                {
                    Stats = runner.GetStats(reset)
                });
            }
            await runner.StopAsync();
        }
Beispiel #57
0
        public async Task Fib(FibArgs request, IServerStreamWriter<Num> responseStream, ServerCallContext context)
        {
            if (request.Limit <= 0)
            {
                // keep streaming the sequence until cancelled.
                IEnumerator<Num> fibEnumerator = FibInternal(long.MaxValue).GetEnumerator();
                while (!context.CancellationToken.IsCancellationRequested && fibEnumerator.MoveNext())
                {
                    await responseStream.WriteAsync(fibEnumerator.Current);
                    await Task.Delay(100);
                }
            }

            if (request.Limit > 0)
            {
                foreach (var num in FibInternal(request.Limit))
                {
                    await responseStream.WriteAsync(num);
                }
            }
        }
Beispiel #58
0
        public override Task <Todo> Get(TodoRequest request, Grpc.Core.ServerCallContext context)
        {
            if (request.Id == 0)
            {
                Logger.LogWarning("id must be greater than 0");
                throw new RpcException(new Status(StatusCode.InvalidArgument, "id must be greater than 0"));
            }

            Todo todo;

            lock (this.mylock)
            {
                if (!this.todos.ContainsKey(request.Id))
                {
                    Logger.LogWarning("id {ID} not found", request.Id);
                    throw new RpcException(new Status(StatusCode.NotFound, $"id {request.Id} not found"));
                }
                todo = this.todos[request.Id];
            }

            return(Task.FromResult(todo));
        }
        public override async Task RunServer(IAsyncStreamReader<ServerArgs> requestStream, IServerStreamWriter<ServerStatus> responseStream, ServerCallContext context)
        {
            GrpcPreconditions.CheckState(await requestStream.MoveNext());
            var serverConfig = requestStream.Current.Setup;
            var runner = ServerRunners.CreateStarted(serverConfig);

            await responseStream.WriteAsync(new ServerStatus
            {
                Stats = runner.GetStats(false),
                Port = runner.BoundPort,
                Cores = Environment.ProcessorCount,
            });
                
            while (await requestStream.MoveNext())
            {
                var reset = requestStream.Current.Mark.Reset;
                await responseStream.WriteAsync(new ServerStatus
                {
                    Stats = runner.GetStats(reset)
                });
            }
            await runner.StopAsync();
        }
 public async Task GetPersonList(PersonListRequest request, IServerStreamWriter<Person> responseStream, ServerCallContext context)
 {
     LogRpc(context);
     foreach (Person person in _personRepository.GetAllPeople())
     {
         await responseStream.WriteAsync(person);
     }
 }