Ejemplo n.º 1
0
        private void racerAdd_Click(object sender, EventArgs e)
        {
            try
            {
                Networking.gRPC.Racer racer = new Networking.gRPC.Racer {
                    Name = Nume.Text, Team = (Networking.gRPC.Team)Enum.Parse(typeof(Networking.gRPC.Team), ((Domain.Team)team.SelectedItem).ToString(), true), Engine = (Networking.gRPC.Engine)Enum.Parse(typeof(Networking.gRPC.Engine), ((Domain.Engine)racerEngine.SelectedItem).ToString(), true)
                };
                Domain.Race          race  = (Domain.Race)racesSelector.SelectedItem;
                Networking.gRPC.Race race1 = new Networking.gRPC.Race {
                    Id = race.id, NoRacers = (uint)race.NoRacers, Date = race.Date.ToString("yyyy-MM-dd").Split()[0], Engine = (Networking.gRPC.Engine)Enum.Parse(typeof(Networking.gRPC.Engine), race.Engine.ToString(), true)
                };
                streamWriter.WriteAsync(new Request {
                    Type = Request.Types.Type.Add, Race = race1, Racer = racer
                });
            }
            catch (NullReferenceException ex1)
            {
                Console.WriteLine(ex1.Message);
                MessageBox.Show("All input fields must be selected and completed", "Ups", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ups", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            Nume.Text          = "Name";
            team.Text          = "Team";
            racerEngine.Text   = "Engine";
            racesSelector.Text = "Races";
        }
Ejemplo n.º 2
0
        private static bool SatisfyDataRequest(
            [NotNull] DataVerificationResponse arg,
            [NotNull] IVerificationDataProvider verificationDataProvider,
            [NotNull] IClientStreamWriter <DataVerificationRequest> callRequestStream)
        {
            DataVerificationRequest result = new DataVerificationRequest();

            try
            {
                if (arg.SchemaRequest != null)
                {
                    result.Schema = verificationDataProvider.GetGdbSchema(arg.SchemaRequest);
                }
                else if (arg.DataRequest != null)
                {
                    result.Data = verificationDataProvider
                                  .GetData(arg.DataRequest).FirstOrDefault();
                }

                callRequestStream.WriteAsync(result);

                return(true);
            }
            catch (Exception e)
            {
                _msg.Debug("Error handling data request", e);

                // Send an empty message to make sure the server does not wait forever:
                callRequestStream.WriteAsync(result);
                throw;
            }
        }
Ejemplo n.º 3
0
        public bool TrySendData(IClientStreamWriter <TRequest> requestStream, TRequest item, int sendTimeoutMs, CancellationToken cancellationToken)
        {
            try
            {
                //If there is no channel, return
                if (cancellationToken.IsCancellationRequested)
                {
                    return(false);
                }

                return(requestStream.WriteAsync(item).Wait(sendTimeoutMs, cancellationToken));
            }
            catch (Exception ex)
            {
                const string errorMessage = "Unable to create gRPC Request/Response Streams";

                var invalidOperEx = ex as InvalidOperationException;
                if (invalidOperEx != null && invalidOperEx.Message == "Request stream has already been completed.")
                {
                    throw new GrpcWrapperStreamNotAvailableException(errorMessage, invalidOperEx);
                }

                var grpcEx = ex as RpcException ?? ex.InnerException as RpcException;
                if (grpcEx != null)
                {
                    throw new GrpcWrapperException(grpcEx.StatusCode, errorMessage, grpcEx);
                }

                throw new GrpcWrapperException(errorMessage, ex);
            }
        }
Ejemplo n.º 4
0
        /// <inheritdoc/>
        public async Task Write(IEnumerable <TagDataPoint> dataPoints)
        {
            var streamTagDataPoints = new PushTagDataPoints();

            streamTagDataPoints.DataPoints.Add(dataPoints.Select(_ => _.ToRuntime()));
            await _serverStreamWriter.WriteAsync(streamTagDataPoints).ConfigureAwait(false);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Writes the specified requests.
 /// </summary>
 /// <typeparam name="TRequest">The type of the request.</typeparam>
 /// <param name="streamWriter"></param>
 /// <param name="requests">The requests.</param>
 /// <returns></returns>
 public static async Task WriteRequestsAsync <TRequest>(this IClientStreamWriter <TRequest> streamWriter, IEnumerable <Task <TRequest> > requests)
 {
     foreach (Task <TRequest> request in requests)
     {
         await streamWriter.WriteAsync(await request.ConfigureAwait(false)).ConfigureAwait(false);
     }
 }
Ejemplo n.º 6
0
        public async Task <long> Publish(ReadOnlyMemory <byte> message)
        {
            Task writeTask;
            long seqNum;

            lock (sync)
            {
                if (disposed)
                {
                    throw new PublisherException($"Cannot write to disposed {nameof(Publisher)}");
                }

                writeTask = requestStream.WriteAsync(new WriteRequest
                {
                    SequenceNumber = sequenceNumber,
                    Message        = Google.Protobuf.ByteString.CopyFrom(message.Span)
                });

                seqNum = sequenceNumber++;
            }

            await writeTask;

            return(seqNum);
        }
Ejemplo n.º 7
0
        public async Task <long> Publish(IEnumerable <ReadOnlyMemory <byte> > messages)
        {
            Task writeTask;
            long seqNum;

            lock (sync)
            {
                if (disposed)
                {
                    throw new PublisherException($"Cannot write to disposed {nameof(Publisher)}");
                }

                var request = new PublishManyRequest
                {
                    SequenceNumber = sequenceNumber
                };

                request.Messages.AddRange(messages.Select(x => Google.Protobuf.ByteString.CopyFrom(x.Span)));

                writeTask = requestStream.WriteAsync(request);

                seqNum = sequenceNumber++;
            }

            await writeTask;

            return(seqNum);
        }
 public async Task StartWriterAsync(IClientStreamWriter <StreamingMessage> requestStream)
 {
     await foreach (StreamingMessage rpcWriteMsg in _outputChannel.Channel.Reader.ReadAllAsync())
     {
         await requestStream.WriteAsync(rpcWriteMsg);
     }
 }
Ejemplo n.º 9
0
        public Task SendPoint(int x, int y, string colorHex)
        {
            System.Drawing.Color col = ColorTranslator.FromHtml(colorHex);
            var drawReq = new DrawPointRequest()
            {
                Id        = id,
                DrawPoint = new DrawPoint()
                {
                    Color = new gRPCClient.Color()
                    {
                        R = (int)col.R,
                        B = (int)col.B,
                        G = (int)col.G
                    },
                    Point = new gRPCClient.Point()
                    {
                        X = x,
                        Y = y
                    }
                }
            };

            _requestStream.WriteAsync(drawReq);
            return(Task.CompletedTask);
        }
Ejemplo n.º 10
0
        private async Task StreamContentAsync(Stream input, byte[] buffer, IClientStreamWriter <PushFileRequest> requestStream, CancellationToken ct)
        {
            Contract.Requires(!(input is null));
            Contract.Requires(!(requestStream is null));

            int chunkSize = 0;

            // Pre-fill buffer with the file's first chunk
            await readNextChunk();

            while (true)
            {
                ct.ThrowIfCancellationRequested();

                if (chunkSize == 0)
                {
                    break;
                }

                ByteString content = ByteString.CopyFrom(buffer, 0, chunkSize);
                var        request = new PushFileRequest()
                {
                    Content = content
                };

                // Read the next chunk while waiting for the response
                await Task.WhenAll(readNextChunk(), requestStream.WriteAsync(request));
            }

            async Task <int> readNextChunk()
            {
                chunkSize = await input.ReadAsync(buffer, 0, buffer.Length, ct); return(chunkSize);
            }
        }
Ejemplo n.º 11
0
 public Task WriteAsync(T message)
 {
     if (onMessage != null)
     {
         message = onMessage(message);
     }
     return(writer.WriteAsync(message));
 }
Ejemplo n.º 12
0
        private async Task SendEnvelopesAsync(IEnumerable <MessageEnvelope> envelopes)
        {
            var batch = new MessageBatch();

            batch.Envelopes.AddRange(envelopes);

            await _streamWriter.WriteAsync(batch);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Writes the specified requests and send a completion.
 /// </summary>
 /// <typeparam name="TRequest">The type of the request.</typeparam>
 /// <param name="streamWriter"></param>
 /// <param name="requests">The requests.</param>
 /// <returns></returns>
 public static async Task WriteRequestsAndCompleteAsync <TRequest>(this IClientStreamWriter <TRequest> streamWriter, IEnumerable <TRequest> requests)
 {
     foreach (TRequest request in requests)
     {
         await streamWriter.WriteAsync(request).ConfigureAwait(false);
     }
     await streamWriter.CompleteAsync().ConfigureAwait(false);
 }
 private async Task WriteAudioIn(byte[] buffer)
 {
     OnDebug?.Invoke("Write Audio " + buffer.Length, true);
     var request = new ConverseRequest()
     {
         AudioIn = ByteString.CopyFrom(buffer)
     };
     await _requestStream.WriteAsync(request);
 }
Ejemplo n.º 15
0
        public Task WriteAsync(T message)
        {
            Task result = _writer.WriteAsync(message);

            result.ContinueWith(task =>
            {
                _onMessage.Invoke();
            });

            return(result);
        }
Ejemplo n.º 16
0
            internal void WriteTo(IClientStreamWriter <T> writer)
            {
                writer.WriteOptions = WriteOptions;
                Task task = Message == null?writer.CompleteAsync() : writer.WriteAsync(Message);

                task.ContinueWith(t =>
                {
                    _continuation?.Invoke(t);
                    PropagateTaskResult(t, CompletionSource);
                });
            }
Ejemplo n.º 17
0
    private async Task Start(CancellationToken token)
    {
        await foreach (var i in _request.WithCancellation(token).ConfigureAwait(false))
        {
            await _stream.WriteAsync(new Message <TRequest>(i)).ConfigureAwait(false);
        }

        if (!token.IsCancellationRequested)
        {
            await _stream.CompleteAsync().ConfigureAwait(false);
        }
    }
Ejemplo n.º 18
0
        private static async Task SendRandomMessage(IClientStreamWriter <Message> requestStrm)
        {
            var randomMessage = new Message
            {
                Id       = Guid.NewGuid().GetHashCode().ToString(),
                Contents = Utilities.RandomSentence()
            };

            await requestStrm.WriteAsync(randomMessage);

            await Task.Delay(1000);
        }
Ejemplo n.º 19
0
        public async Task Complete(long messageId)
        {
            if (disposed)
            {
                throw new SubscriberException($"Cannot write to disposed {nameof(Subscriber)}");
            }

            await requestStream.WriteAsync(new FastQueueService.CompleteRequest
            {
                Id = messageId
            });
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Writes all elements from given enumerable to the stream.
 /// Completes the stream afterwards unless close = false.
 /// </summary>
 public static async Task WriteAllAsync <T>(this IClientStreamWriter <T> streamWriter, IEnumerable <T> elements, bool complete = true)
     where T : class
 {
     foreach (var element in elements)
     {
         await streamWriter.WriteAsync(element).ConfigureAwait(false);
     }
     if (complete)
     {
         await streamWriter.CompleteAsync().ConfigureAwait(false);
     }
 }
Ejemplo n.º 21
0
        private static async Task MyPlay(IClientStreamWriter <GameRequest> request)
        {
            //
            // client play
            //
            var myDice = await client.RollDiceAsync(new EmptyRequest());

            var clientResult = $"Client Result: {myDice.Result}";

            Console.WriteLine(clientResult);

            await request.WriteAsync(new GameRequest { ClientResult = clientResult });
        }
Ejemplo n.º 22
0
 private async Task SendEnvelopesAsync(MessageBatch batch, IContext context)
 {
     try
     {
         await _streamWriter.WriteAsync(batch);
     }
     catch (Exception x)
     {
         context.Stash();
         Console.WriteLine($"[REMOTING] gRPC Failed to send to address {_address}, reason {x.Message}");
         throw;
     }
 }
Ejemplo n.º 23
0
        private async Task ListServices(IClientStreamWriter <ServerReflectionRequest> req, ListServiceResponse resp)
        {
            var services = resp.Service.Where(p => !p.Name.StartsWith("grpc."));

            foreach (var service in services)
            {
                await req.WriteAsync(new ServerReflectionRequest()
                {
                    FileContainingSymbol = service.Name
                });
            }
            await req.CompleteAsync();
        }
Ejemplo n.º 24
0
 private async Task SendEnvelopesAsync(MessageBatch batch, IContext context)
 {
     try
     {
         await _streamWriter.WriteAsync(batch);
     }
     catch (Exception x)
     {
         context.Stash();
         _logger.LogError($"gRPC Failed to send to address {_address}, reason {x.Message}");
         throw;
     }
 }
        public async Task SendStartStreamMessageAsync(IClientStreamWriter <StreamingMessage> requestStream)
        {
            StartStream str = new StartStream()
            {
                WorkerId = _options.WorkerId
            };

            StreamingMessage startStream = new StreamingMessage()
            {
                StartStream = str
            };

            await requestStream.WriteAsync(startStream);
        }
Ejemplo n.º 26
0
 private static async Task WriteStream(IClientStreamWriter <PostForecastRequest> requestStream)
 {
     await foreach (var f in ForecastFactory.CreateMultipleAsync(10))
     {
         await requestStream.WriteAsync(new PostForecastRequest
         {
             Date           = f.date,
             TemperatureC   = f.temperatureC,
             Summary        = f.summary,
             CanYouPlayGolf = f.canYouPlayGolf
         });
     }
     await requestStream.CompleteAsync();
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Sends a single ping to designate that the Game Server is alive and healthy.
        /// </summary>
        /// <returns>gRPC Status of the request</returns>
        internal async Task <Status> HealthAsync()
        {
            try
            {
                await healthStream.WriteAsync(new Empty());

                return(new Status(StatusCode.OK, "Health ping successful."));
            }
            catch (RpcException ex)
            {
                Console.Error.WriteLine(ex.Message);
                return(ex.Status);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Sends a single ping to designate that the Game Server is alive and healthy.
        /// </summary>
        /// <returns>gRPC Status of the request</returns>
        public async Task <Status> HealthAsync()
        {
            try
            {
                await healthStream.WriteAsync(new Empty());

                return(new Status(StatusCode.OK, "Health ping successful."));
            }
            catch (RpcException ex)
            {
                LogError(ex, "Unable to invoke the GameServer health check.");
                return(ex.Status);
            }
        }
        async Task WritePong(CancellationToken cancellationToken)
        {
            await _writeResponseSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    _logger.Debug("Reverse Call Client was cancelled before it could respond with pong");
                    return;
                }

                var message = new TClientMessage();
                _setPong(message, new Pong());

                _logger.Trace("Writing pong");
                await _clientToServer.WriteAsync(message).ConfigureAwait(false);
            }
            finally
            {
                _writeResponseSemaphore.Release();
            }
        }
Ejemplo n.º 30
0
        private async Task SatisfyDataQueryAsync(
            [NotNull] DataRequest dataRequest,
            [NotNull] IClientStreamWriter <DataVerificationRequest> targetStream)
        {
            // Once the result messages are split up, this could be used for higher throughput
            foreach (GdbData data in Assert.NotNull(VerificationDataProvider).GetData(dataRequest))
            {
                DataVerificationRequest r = new DataVerificationRequest
                {
                    Data = data
                };

                await targetStream.WriteAsync(r);
            }
        }