/// <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 async Task <RouteSummary> RecordRoute(Grpc.Core.ServerCallContext context, Grpc.Core.IAsyncStreamReader <Point> requestStream)
        {
            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 (RouteGuideUtil.Exists(CheckFeature(point)))
                {
                    featureCount++;
                }
                if (previous != null)
                {
                    distance += (int)CalcDistance(previous, point);
                }
                previous = point;
            }

            stopwatch.Stop();
            return(RouteSummary.CreateBuilder().SetPointCount(pointCount)
                   .SetFeatureCount(featureCount).SetDistance(distance)
                   .SetElapsedTime((int)(stopwatch.ElapsedMilliseconds / 1000)).Build());
        }
        public override Task <Stop.Types.Response> Stop(
            Stop.Types.Request request, Grpc.Core.ServerCallContext context)
        {
            var response = new Stop.Types.Response();

            var providerType = _schemaResolver.PluginDetails.Provider;

            if (providerType.HasStopSkill())
            {
                providerType.InvokeStopSkill(
                    PluginProviderInstance,
                    readResult: (resultType, result) => {
                    var error = ((HasStop.Result)result).Error;
                    if (!string.IsNullOrEmpty(error))
                    {
                        response.Error = error;
                    }
                });
            }

            _log.LogInformation("Stopping Plugin Server");
            _pluginServer.Stop();

            return(Task.FromResult(response));
        }
Exemple #3
0
 public override Task <HelloReply> SayHello(HelloRequest request, Grpc.Core.ServerCallContext context)
 {
     Console.WriteLine("Request:" + request.Name);
     return(Task.FromResult(new HelloReply {
         Message = "Hello " + request.Name
     }));
 }
Exemple #4
0
        public override async Task StartStream(
            Grpc.Core.IAsyncStreamReader <Plugin.ConnInfo> requestStream,
            Grpc.Core.IServerStreamWriter <Plugin.ConnInfo> responseStream,
            Grpc.Core.ServerCallContext context)
        {
            var cts = CancellationTokenSource.CreateLinkedTokenSource(
                _pluginHost.StopHostingToken, context.CancellationToken);

            _log.LogInformation("Starting streaming...");
            var ct = cts.Token;

            try
            {
                while (!ct.IsCancellationRequested)
                {
                    while (await requestStream.MoveNext(ct))
                    {
                        var connInfo = requestStream.Current;
                        _log.LogWarning("Not sure what to do -- got connection info:  {@conninfo}", connInfo);
                        await responseStream.WriteAsync(connInfo);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                _log.LogWarning("Operation has been canceled");
            }

            _log.LogInformation("Streaming completed");
        }
Exemple #5
0
 public override Task <PongReply> Ping(Empty request, Grpc.Core.ServerCallContext context)
 {
     return(Task.FromResult(new PongReply
     {
         Message = "Contact service pong"
     }));
 }
        public override async Task DirectorRegistration(RegisterToRecieveAnalyzerMessages msg,
                                                        Grpc.Core.IServerStreamWriter <NewLineCrossingEvent> responseStream,
                                                        Grpc.Core.ServerCallContext context)
        {
            await MailBag.Get().DirectorMessageLoop(responseStream);

            await Task.Delay(-1);
        }
Exemple #7
0
        public override Task <SignatureResponse> Generate(SignatureRequest request, Grpc.Core.ServerCallContext context)
        {
            var byteString = Sign(request.LicenseKey);

            return(Task.FromResult(new SignatureResponse {
                Signature = Convert.ToBase64String(byteString)
            }));
        }
Exemple #8
0
        public override Task <Empty> Put(Proto.PutRequest request,
                                         Grpc.Core.ServerCallContext context)
        {
            _log.LogInformation("Got Put with [{0}]=[{1}]", request.Key,
                                request.Value.ToStringUtf8());

            return(Task.FromResult(DefaultEmpty));
        }
        public override Task <MyReply> SendRequest(MyRequest request, Grpc.Core.ServerCallContext context)
        {
            Console.WriteLine($"Server received message '{request.Message}'");
            var reply = new MyReply();

            reply.Message = $"Received message: {request.Message}";
            reply.Foo     = new Random().Next();
            return(Task.FromResult(reply));
        }
Exemple #10
0
        public override Task <TeaResponses> GetAllTea(Empty request, Grpc.Core.ServerCallContext context)
        {
            //return base.GetAllTea(request, context);
            var tr = new TeaResponses
            {
                Names = { Teas }
            };

            return(Task.FromResult(tr));
        }
Exemple #11
0
 // Server side handler of the SayHello RPC
 public override Task <IntegerMessage> AddOne(IntegerMessage request, Grpc.Core.ServerCallContext context)
 {
     return(Task.Run(() =>
     {
         Console.WriteLine($"Receive Request: Value = {request.Value}, Message = {request.Message}");
         return new IntegerMessage {
             Value = request.Value + 1, Message = request.Message
         };
     }));
 }
        public override Task <CoffeeResponse> GetRandomCoffee(Empty request, Grpc.Core.ServerCallContext context)
        {
            //return base.GetRandomCoffee(request, context);
            var            rnd = new Random();
            var            t   = Coffees[rnd.Next(Coffees.Length)];
            CoffeeResponse tr  = new CoffeeResponse {
                Name = t
            };

            return(Task.FromResult(tr));
        }
Exemple #13
0
        public static string GetGrpcPeerIp(Grpc.Core.ServerCallContext context)
        {
            const char SEPARATOR = ':';
            var        source    = context.Peer; // "ipv4:ip:port" or "ipv6:[ip]:port" ; ipv6 url 주소에서는 [,] 가 쓰임. https://tools.ietf.org/html/rfc2732
            var        sep1      = source.IndexOf(SEPARATOR);
            var        sep2      = source.LastIndexOf(SEPARATOR);
            //var version = source.Substring(0, sep1);
            var ip = source.Substring(sep1 + 1, sep2 - sep1 - 1);

            return(ip);
        }
        public override Task <NameAndSurname> Search(Request request, Grpc.Core.ServerCallContext context)
        {
            var entry = mockRepo[request.Id];

            var response = new NameAndSurname()
            {
                Name = entry.Name, Surname = entry.Surname
            };

            return(Task.FromResult(response));
        }
Exemple #15
0
        public override Task <TeaResponse> GetRandomTea(Empty request, Grpc.Core.ServerCallContext context)
        {
            //return base.GetRandomTea(request, context);
            var         rnd = new Random();
            var         t   = Teas[rnd.Next(Teas.Length)];
            TeaResponse tr  = new TeaResponse {
                Name = t
            };

            return(Task.FromResult(tr));
        }
Exemple #16
0
        public override Task <AuthResponse> SignUp(SignUpUserData user, Grpc.Core.ServerCallContext context)
        {
            // TODO

            /*
            ** Save new user in database
            ** Generate token
            ** Return token and 200 status
            */
            return(Task.FromResult(new AuthResponse {
                Status = 200, Token = "Token"
            }));
        }
Exemple #17
0
        public override Task <AuthResponse> SignIn(SignInUserData user, Grpc.Core.ServerCallContext context)
        {
            // TODO

            /*
            ** Check if user with provided data exists in database
            ** if not return unauthenticated
            ** generate token
            ** Return token and 200 status
            */
            return(Task.FromResult(new AuthResponse {
                Status = 200, Token = "Token"
            }));
        }
        public async override Task <Empty> EventChange(Changes eventChanges, Grpc.Core.ServerCallContext context)
        {
            if (eventChanges is null)
            {
                return(new Empty());
            }

            var oldEventData = mapper.Map <EventDTO>(eventChanges.OldEventData);
            var newEventData = mapper.Map <EventDTO>(eventChanges.NewEventData);

            await telegramBotService.SendEventChangesAsync(TelegramBotService.EventsChannelId, oldEventData, newEventData);

            return(new Empty());
        }
Exemple #19
0
        public override Task <GetResponse> Get(Proto.GetRequest request,
                                               Grpc.Core.ServerCallContext context)
        {
            _log.LogInformation("Got Get with [{0}]", request.Key);

            // Artificial delay...
            Thread.Sleep(15 * 1000);

            return(Task.FromResult(new GetResponse
            {
                Value = ByteString.CopyFromUtf8(
                    $"{request.Key}=[{request.Key.ToUpper()}]"),
            }));
        }
Exemple #20
0
 public override Task <Product> GetProductById(ProductByIdRequest request, Grpc.Core.ServerCallContext context)
 {
     Console.WriteLine($"{nameof(ProductService)} | {nameof(GetProductById)} | Request: {request.ProductId}");
     if (request.ProductId == 1)
     {
         return(Task.FromResult(new Product
         {
             ProductId = 1,
             ProductUuid = "Id Of Product 1"
         }));
     }
     else
     {
         throw new Exception("Product not found");
     }
 }
        public override Task <Empty> Shutdown(Plugin.Empty request, Grpc.Core.ServerCallContext context)
        {
            _log.LogInformation("Got request for Shutdown, initiating...");

            if (OnShutdown != null)
            {
                _log.LogInformation("Custom handler found, invoking");
            }
            else
            {
                _log.LogInformation("Invoking default behavior, stopping Plugin Host");
                _pluginHost.StopHosting();
            }

            return(Task.FromResult(DefaultEmpty));
        }
Exemple #22
0
        public override Task <ProductsResponse> Get(Empty _, Grpc.Core.ServerCallContext context)
        {
            var maps = products
                       .Select(p => new ProductResponse()
            {
                Id        = p.Id.ToString(),
                CreatedAt = Timestamp.FromDateTimeOffset(p.CreatedAt),
                Name      = p.Name,
                Sku       = p.Sku,
                Price     = p.Price
            });

            var @return = new ProductsResponse();

            @return.Products.AddRange(maps);
            return(Task.FromResult(@return));
        }
        /// <summary>
        /// Gets all features contained within the given bounding rectangle.
        /// </summary>
        public async Task ListFeatures(Grpc.Core.ServerCallContext context, Rectangle request, Grpc.Core.IServerStreamWriter <Feature> responseStream)
        {
            int left   = Math.Min(request.Lo.Longitude, request.Hi.Longitude);
            int right  = Math.Max(request.Lo.Longitude, request.Hi.Longitude);
            int top    = Math.Max(request.Lo.Latitude, request.Hi.Latitude);
            int bottom = Math.Min(request.Lo.Latitude, request.Hi.Latitude);

            foreach (var feature in features)
            {
                if (!RouteGuideUtil.Exists(feature))
                {
                    continue;
                }

                int lat = feature.Location.Latitude;
                int lon = feature.Location.Longitude;
                if (lon >= left && lon <= right && lat >= bottom && lat <= top)
                {
                    await responseStream.WriteAsync(feature);
                }
            }
        }
        public override Task <GetProviderSchema.Types.Response> GetSchema(
            GetProviderSchema.Types.Request request,
            Grpc.Core.ServerCallContext context)
        {
            var response = new GetProviderSchema.Types.Response();

            response.Provider = _schemaResolver.GetProviderConfigurationSchema().Schema;
            _log.LogInformation("Resolved Schema for Provider implemented by [{provider}]",
                                _schemaResolver.PluginDetails.Provider);

            foreach (var schema in _schemaResolver.GetDataSourceSchemas().Values)
            {
                response.DataSourceSchemas.Add(schema.Name, schema.Schema);
                _log.LogInformation("Resolved Schema for Data Source [{name}]", schema.Name);
            }

            foreach (var schema in _schemaResolver.GetResourceSchemas().Values)
            {
                response.ResourceSchemas.Add(schema.Name, schema.Schema);
                _log.LogInformation("Resolved Schema for Data Source [{name}]", schema.Name);
            }

            return(Task.FromResult(response));
        }
        /// <summary>
        /// Receives a stream of message/location pairs, and responds with a stream of all previous
        /// messages at each of those locations.
        /// </summary>
        public async Task RouteChat(Grpc.Core.ServerCallContext context, Grpc.Core.IAsyncStreamReader <RouteNote> requestStream, Grpc.Core.IServerStreamWriter <RouteNote> responseStream)
        {
            while (await requestStream.MoveNext())
            {
                var note = requestStream.Current;
                List <RouteNote> notes = GetOrCreateNotes(note.Location);

                List <RouteNote> prevNotes;
                lock (notes)
                {
                    prevNotes = new List <RouteNote>(notes);
                }

                foreach (var prevNote in prevNotes)
                {
                    await responseStream.WriteAsync(prevNote);
                }

                lock (notes)
                {
                    notes.Add(note);
                }
            }
        }
        public async override Task <PlaceOrderReply> PlaceOrder(PlaceOrderRequest request, Grpc.Core.ServerCallContext context)
        {
            var order = FromGrpc(request);

            db.Orders.Attach(order);
            await db.SaveChangesAsync();

            var database = multiplexer.GetDatabase();
            await database.ListRightPushAsync("orders", JsonSerializer.Serialize(order, options));

            var subscriber = multiplexer.GetSubscriber();
            await subscriber.PublishAsync("neworder", "");

            return(new PlaceOrderReply()
            {
                Id = order.OrderId,
            });
        }
        public async override Task <OrderDetailsReply> GetOrderDetails(OrderDetailsRequest request, Grpc.Core.ServerCallContext context)
        {
            var order = await db.Orders
                        .Where(o => o.OrderId == request.OrderId)
                        .Where(o => o.UserId == request.UserId)
                        .Include(o => o.DeliveryLocation)
                        .Include(o => o.Pizzas).ThenInclude(p => p.Special)
                        .Include(o => o.Pizzas).ThenInclude(p => p.Toppings).ThenInclude(t => t.Topping)
                        .SingleOrDefaultAsync();

            var reply = new OrderDetailsReply
            {
                Order = order?.ToGrpc()
            };

            return(reply);
        }
        public async override Task <OrderHistoryReply> GetOrderHistory(OrderHistoryRequest request, Grpc.Core.ServerCallContext context)
        {
            var orders = await db.Orders
                         .Where(o => o.UserId == request.UserId)
                         .Include(o => o.DeliveryLocation)
                         .Include(o => o.Pizzas).ThenInclude(p => p.Special)
                         .Include(o => o.Pizzas).ThenInclude(p => p.Toppings).ThenInclude(t => t.Topping)
                         .ToListAsync();

            var reply = new OrderHistoryReply();

            reply.Orders.Add(orders.Select(o => o.ToGrpc()));
            return(reply);
        }
Exemple #29
0
        /// <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 async Task <RouteSummary> RecordRoute(Grpc.Core.IAsyncStreamReader <Point> requestStream, Grpc.Core.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)
            });
        }
Exemple #30
0
        /// <summary>
        /// Gets all features contained within the given bounding rectangle.
        /// </summary>
        public async Task ListFeatures(Rectangle request, Grpc.Core.IServerStreamWriter <Feature> responseStream, Grpc.Core.ServerCallContext context)
        {
            var responses = features.FindAll((feature) => feature.Exists() && request.Contains(feature.Location));

            foreach (var response in responses)
            {
                await responseStream.WriteAsync(response);
            }
        }