コード例 #1
0
 public ActionResult <object> SelectById(int id)
 {
     try
     {
         var item = _userService.GetOne(id);
         if (item == null)
         {
             var toSerialize = new MessageHelpers <UserViewModel>()
             {
                 Status = 404,
                 Data   = null
             };
             return(JsonConvert.SerializeObject(toSerialize));
         }
         else
         {
             var toSerialize = new MessageHelpers <UserViewModel>()
             {
                 Status = 200,
                 Data   = new List <UserViewModel> {
                     item
                 }
             };
             return(JsonConvert.SerializeObject(toSerialize));
         }
     }
     catch
     {
         var toSerialize = new MessageHelpers <UserViewModel>()
         {
             Status = 502,
             Data   = null
         };
         return(JsonConvert.SerializeObject(toSerialize));
     }
 }
コード例 #2
0
        public async Task InterceptorsExecutedInRegistrationOrder_AndGlobalInterceptorExecutesFirst_DuplexStreaming()
        {
            // Arrange
            var url = Fixture.DynamicGrpc.AddDuplexStreamingMethod <Empty, Empty>((requestStream, responseStream, context) =>
            {
                var items = context.GetHttpContext().Items;
                Assert.AreEqual(3, items[OrderedInterceptor.OrderHeaderKey]);
                return(Task.CompletedTask);
            });

            // Act
            var response = await Fixture.Client.PostAsync(
                url,
                new GrpcStreamContent(new MemoryStream())).DefaultTimeout();

            var responseStream = await response.Content.ReadAsStreamAsync().DefaultTimeout();

            var pipeReader = PipeReader.Create(responseStream);

            // Assert
            await MessageHelpers.AssertReadStreamMessageAsync <Empty>(pipeReader).DefaultTimeout();

            response.AssertTrailerStatus();
        }
コード例 #3
0
        public async Task HttpContextAccessor_ReturnContextInTrailer()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage);

            var httpRequest = GrpcHttpHelper.Create("Greet.Greeter/MethodDoesNotExist");

            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            response.AssertIsSuccessfulGrpcRequest();

            response.AssertTrailerStatus(StatusCode.Unimplemented, "Method is unimplemented.");
        }
コード例 #4
0
        public async Task SendValidRequest_SuccessResponse()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            // Act
            var response = await Fixture.Client.PostAsync(
                "Greet.Greeter/SayHello",
                new GrpcStreamContent(ms)).DefaultTimeout();

            // Assert
            var responseMessage = await response.GetSuccessfulGrpcMessageAsync <HelloReply>();

            Assert.AreEqual("Hello World", responseMessage.Message);

            Assert.AreEqual(StatusCode.OK.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].Single());
        }
コード例 #5
0
 public void DeleteRecord()
 {
     try
     {
         var    sectioncode = mgridList.Rows[mgridList.SelectedCells[0].RowIndex].Cells["colSectionCode"].Value.ToString();
         string scode       = sectioncode;
         if (MessageHelpers.ShowQuestion("Are you sure you want to delete record?") == System.Windows.Forms.DialogResult.Yes)
         {
             var DeletingisSuccess = false;
             var msg = "Deleting";
             sect = Sectionbal.GetByID(sectioncode);
             if (Sectionbal.Delete(sect))
             {
                 DeletingisSuccess = true;
             }
             if (DeletingisSuccess)
             {
                 MessageHelpers.ShowInfo(msg + " Successful!");
                 RefreshGrid();
                 PageManager(1);
             }
             else
             {
                 MessageHelpers.ShowWarning(msg + " Failed!");
             }
         }
     }
     catch (Exception ex)
     {
         MessageHelpers.ShowError(ex.Message);
     }
     finally
     {
         FormHelpers.CursorWait(false);
     }
 }
コード例 #6
0
        public void GlobalSetup()
        {
            var marshaller = Marshallers.Create((arg) => MessageExtensions.ToByteArray(arg), bytes => new ChatMessage());
            var method     = new Method <ChatMessage, ChatMessage>(MethodType.Unary, typeof(TestService).FullName, nameof(TestService.SayHello), marshaller, marshaller);
            var result     = Task.FromResult(new ChatMessage());

            _callHandler = new UnaryServerCallHandler <TestService, ChatMessage, ChatMessage>(
                method,
                (service, request, context) => result,
                new GrpcServiceOptions(),
                NullLoggerFactory.Instance);

            _trailers = new HeaderDictionary();

            var message = new ChatMessage
            {
                Name = "Joe"
            };

            _requestStream = new MemoryStream();
            MessageHelpers.WriteMessage(_requestStream, message);

            var services = new ServiceCollection();

            services.TryAddSingleton <IGrpcServiceActivator <TestService> >(new TestGrpcServiceActivator <TestService>(new TestService()));
            _requestServices = services.BuildServiceProvider();

            _httpContext = new DefaultHttpContext();
            _httpContext.RequestServices = _requestServices;
            _httpContext.Request.Body    = _requestStream;

            _httpContext.Features.Set <IHttpResponseTrailersFeature>(new TestHttpResponseTrailersFeature
            {
                Trailers = _trailers
            });
        }
コード例 #7
0
        public async Task UnimplementedContentType_ReturnUnimplementedForAppGrpc(string contentType, HttpStatusCode httpStatusCode, StatusCode?grpcStatusCode)
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage);

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "HasMapped/Extra");

            httpRequest.Content = new StreamContent(requestStream);
            httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            Assert.AreEqual(httpStatusCode, response.StatusCode);
            Assert.AreEqual(grpcStatusCode?.ToTrailerString() ?? string.Empty, Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].ToString());
        }
コード例 #8
0
        public async Task HttpContextAccessor_ReturnContextInTrailer()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage);

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Greet.Greeter/SayHelloWithHttpContextAccessor?query=extra");

            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            response.AssertIsSuccessfulGrpcRequest();
            Fixture.AssertTrailerStatus();
            Assert.AreEqual("/Greet.Greeter/SayHelloWithHttpContextAccessor?query=extra", Fixture.TrailersContainer.Trailers["Test-HttpContext-PathAndQueryString"].ToString());
        }
コード例 #9
0
        public async Task MultipleMessagesThenClose_SuccessResponse()
        {
            // Arrange
            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, new CounterRequest
            {
                Count = 1
            });

            var httpRequest = GrpcHttpHelper.Create("Count.Counter/AccumulateCount");

            httpRequest.Content = new PushStreamContent(
                async s =>
            {
                await s.WriteAsync(ms.ToArray()).AsTask().DefaultTimeout();
                await s.FlushAsync().DefaultTimeout();

                await s.WriteAsync(ms.ToArray()).AsTask().DefaultTimeout();
                await s.FlushAsync().DefaultTimeout();
            });

            // Act
            var responseTask = Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);

            // Assert
            Assert.IsFalse(responseTask.IsCompleted, "Server should wait for client to finish streaming");


            var response = await responseTask.DefaultTimeout();

            var reply = await response.GetSuccessfulGrpcMessageAsync <CounterReply>().DefaultTimeout();

            Assert.AreEqual(2, reply.Count);
            response.AssertTrailerStatus();
        }
コード例 #10
0
        public async Task HttpContextExtensionMethod_ReturnContextInTrailer()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage);

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Greet.ServiceDoesNotExist/Method");

            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            response.AssertIsSuccessfulGrpcRequest();

            Fixture.AssertTrailerStatus(StatusCode.Unimplemented, "Service is unimplemented.");
        }
コード例 #11
0
 private void DeleteEntry()
 {
     try
     {
         FormHelpers.CursorWait(true);
         var    selgrp     = mgridList.Rows[mgridList.SelectedCells[0].RowIndex].Cells["colUserGroupDesc"].Value;
         string selgrpcode = mgridList.Rows[mgridList.SelectedCells[0].RowIndex].Cells["colUserGroupCode"].Value.ToString();
         if (MessageHelpers.ShowQuestion("Do want to delete " + selgrp + " group?") == System.Windows.Forms.DialogResult.Yes)
         {
             if (usergroupbal.Delete(selgrpcode))
             {
                 MessageHelpers.ShowInfo(selgrp + " group deleted successfully!");
             }
         }
     }
     catch (Exception ex)
     {
         MessageHelpers.ShowError(ex.Message);
     }
     finally
     {
         FormHelpers.CursorWait(false);
     }
 }
コード例 #12
0
        private void mbtnModify_Click(object sender, EventArgs e)
        {
            var msg_asking = "";

            if (signalist_existing.Count == 0)
            {
                msg_asking = "save";
            }
            else
            {
                msg_asking = "update";
            }

            switch (MyState)
            {
            case FormState.Edit:
                try
                {
                    if (MessageHelpers.ShowQuestion("Are you sure you want to " + msg_asking + " record?") == System.Windows.Forms.DialogResult.Yes)
                    {
                        SaveRecord();
                    }
                }
                catch (Exception ex)
                {
                    MessageHelpers.ShowError(ex.Message);
                }
                break;

            default:
                MyState         = FormState.Edit;
                mbtnModify.Text = "Update";
                LockFields(false);
                break;
            }
        }
コード例 #13
0
        public ActionResult <object> Create([FromBody] LoginModel login)
        {
            /*
             * var client = new RestClient("localhost:44341/api/token");
             *  client.Timeout = -1;
             *  var request = new RestRequest(Method.POST);
             *  request.AddHeader("Content-Type", "application/json");
             *  request.AddParameter("application/json", "{\n    \"Username\": \"jpd21122012\",\n    \"Password\": \"12345\"\n}",  ParameterType.RequestBody);
             *  IRestResponse response = client.Execute(request);
             *  Console.WriteLine(response.Content);
             */
            var user = Authenticate(login);

            if (user != null)
            {
                var tokenString = BuildToken(user);
                var toSerialize = new MessageHelpers <TokenHelper>()
                {
                    Status = 200,
                    Data   = new List <TokenHelper> {
                        tokenString
                    }
                };
                return(JsonConvert.SerializeObject(toSerialize));
            }
            else
            {
                var tokenString = BuildToken(user);
                var toSerialize = new MessageHelpers <TokenHelper>()
                {
                    Status = 401,
                    Data   = null
                };
                return(JsonConvert.SerializeObject(toSerialize));
            }
        }
コード例 #14
0
 public void RefreshGrid()
 {
     try
     {
         var       list    = mtbal.GetByYear(UserSettings.LogInYear).Distinct().Where(w => w.Process == BPSUtilitiesV1.NZ(mcboProcess.SelectedValue, "").ToString()).ToList();
         DataTable mtTable = new DataTable();
         using (var reader = ObjectReader.Create(list,
                                                 "PartNo",
                                                 "PartName",
                                                 "Usage",
                                                 "Vendor"))
         {
             mtTable.Load(reader);
             mgridList.DataSource = mtTable;
         }
         dgvorig.DataSource = mgridList.DataSource;
         Grid.ListCheck(mgridList, listTS);
         tslblRowCount.Text = "Number of Records:    " + list.Count + "       ";
     }
     catch (Exception ex)
     {
         MessageHelpers.ShowError(ex.Message);
     }
 }
コード例 #15
0
 public void RemoveYear()
 {
     try
     {
         FormHelpers.CursorWait(true);
         var recyear = mgridYearList.SelectedRows[0].Cells["colYear"].Value.ToString();
         if (MessageHelpers.ShowQuestion("Are you sure you want to remove this year?") == DialogResult.Yes)
         {
             var RemovingisSuccess = false;
             var msg = "Removing";
             fxsp = yearbal.CheckFXSPYear(Convert.ToInt32(recyear));
             cat  = yearbal.CheckCatYear(Convert.ToInt32(recyear));
             if (yearbal.Remove(Convert.ToInt32(recyear)))
             {
                 RemovingisSuccess = true;
             }
             if (RemovingisSuccess)
             {
                 MessageHelpers.ShowInfo(msg + " Successful!");
                 RefreshGrid();
             }
             else
             {
                 MessageHelpers.ShowWarning(msg + " Failed!");
             }
         }
     }
     catch (Exception ex)
     {
         MessageHelpers.ShowError(ex.Message);
     }
     finally
     {
         FormHelpers.CursorWait(false);
     }
 }
コード例 #16
0
        public async Task CallAuthorizedServiceWithInvalidToken_ReturnUnauthorized()
        {
            // Arrange

            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Authorize.AuthorizedGreeter/SayHello");

            httpRequest.Headers.Add("Authorization", $"Bearer SomeInvalidTokenHere");
            httpRequest.Content = new GrpcStreamContent(ms);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest);

            // Assert
            Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
        }
コード例 #17
0
        public async Task AdditionalDataAfterStreamedMessage_ErrorResponse()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            var requestStream = new SyncPointMemoryStream();

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Greet.Greeter/SayHello");

            httpRequest.Content = new StreamContent(requestStream);

            // Act
            var responseTask = Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);

            // Assert
            Assert.IsFalse(responseTask.IsCompleted, "Server should wait for client to finish streaming");

            await requestStream.AddDataAndWait(ms.ToArray()).DefaultTimeout();

            await requestStream.AddDataAndWait(ms.ToArray()).DefaultTimeout();

            // TODO - this should return a response with a gRPC status object
            var ex = Assert.ThrowsAsync <InvalidDataException>(async() =>
            {
                await responseTask.DefaultTimeout();
            });

            Assert.AreEqual("Additional data after the message received.", ex.Message);
        }
コード例 #18
0
        public async Task MultipleMessagesThenClose_SuccessResponse()
        {
            // Arrange
            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, new CounterRequest
            {
                Count = 1
            });

            var requestStream = new SyncPointMemoryStream();

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "Count.Counter/AccumulateCount");

            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var responseTask = Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);

            // Assert
            Assert.IsFalse(responseTask.IsCompleted, "Server should wait for client to finish streaming");

            await requestStream.AddDataAndWait(ms.ToArray()).DefaultTimeout();

            await requestStream.AddDataAndWait(ms.ToArray()).DefaultTimeout();

            await requestStream.AddDataAndWait(Array.Empty <byte>()).DefaultTimeout();

            var response = await responseTask.DefaultTimeout();

            var reply = await response.GetSuccessfulGrpcMessageAsync <CounterReply>();

            Assert.AreEqual(2, reply.Count);

            Assert.AreEqual(StatusCode.OK.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].Single());
        }
コード例 #19
0
        public void GlobalSetup()
        {
            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, new HelloReply());
            var requestMessage = ms.ToArray();

            var handler = TestHttpMessageHandler.Create(r =>
            {
                var content = new ByteArrayContent(requestMessage);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/grpc");

                return(Task.FromResult(ResponseUtils.CreateResponse(HttpStatusCode.OK, content)));
            });

            var httpClient = new HttpClient(handler);

            var channel = GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions
            {
                HttpClient = httpClient
            });

            _client = new Greeter.GreeterClient(channel);
        }
コード例 #20
0
 public void RefreshGrid()
 {
     try
     {
         var       list      = Sectionbal.GetAll().Distinct().OrderBy(m => m.SECTIONDESC).ToList();
         DataTable sectTable = new DataTable();
         using (var reader = ObjectReader.Create(list,
                                                 "RecID",
                                                 "SECTIONCODE",
                                                 "SECTIONDESC",
                                                 "IsActive"))
         {
             sectTable.Load(reader);
             mgridList.DataSource = sectTable;
         }
         dgvorig.DataSource = mgridList.DataSource;
         Grid.ListCheck(mgridList, listTS);
         tslblRowCount.Text = "Number of Records:    " + list.Count + "       ";
     }
     catch (Exception ex)
     {
         MessageHelpers.ShowError(ex.Message);
     }
 }
コード例 #21
0
ファイル: ZyanMethodQueryHandler.cs プロジェクト: zyanfx/Zyan
        public IQueryable <T> Get <T>() where T : class
        {
            if (querySession == null)
            {
                throw new InvalidOperationException("Session is not started. ZyanMethodQueryHandler requires that StartSession method is called before Get<T>.");
            }

            // get component instance created by
            var instance     = querySession.Instance;
            var instanceType = instance.GetType();

            // create generic method
            var genericMethodInfo = instanceType.GetMethod(MethodInfo.Name, new[] { typeof(T) }, new Type[0]);

            if (genericMethodInfo == null)
            {
                var methodSignature  = MessageHelpers.GetMethodSignature(instanceType, MethodInfo.Name, new Type[0]);
                var exceptionMessage = string.Format(LanguageResource.MissingMethodException_MethodNotFound, methodSignature);
                throw new MissingMethodException(exceptionMessage);
            }

            // invoke Get<T> method and return IQueryable<T>
            object result = genericMethodInfo.Invoke(instance, new object[0]);

            if (result is IQueryable <T> )
            {
                return(result as IQueryable <T>);
            }

            if (result is IEnumerable <T> )
            {
                return((result as IEnumerable <T>).AsQueryable());
            }

            return(null);
        }
コード例 #22
0
        public async Task SendUnsupportedEncodingHeaderWithUncompressedMessage_ReturnUncompressedMessage()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage);

            var httpRequest = GrpcHttpHelper.Create("Greet.Greeter/SayHello");

            httpRequest.Headers.Add(GrpcProtocolConstants.MessageEncodingHeader, "DOES_NOT_EXIST");
            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest).DefaultTimeout();

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            response.AssertTrailerStatus();
        }
コード例 #23
0
        public async Task InterceptorsExecutedInRegistrationOrder_AndGlobalInterceptorExecutesFirst_Unary()
        {
            // Arrange
            var url = Fixture.DynamicGrpc.AddUnaryMethod <Empty, Empty>((request, context) =>
            {
                var items = context.GetHttpContext().Items;
                Assert.AreEqual(3, items[OrderedInterceptor.OrderHeaderKey]);
                return(Task.FromResult(new Empty()));
            });

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, new Empty());

            // Act
            var response = await Fixture.Client.PostAsync(
                url,
                new GrpcStreamContent(ms)).DefaultTimeout();

            // Assert
            var responseMessage = await response.GetSuccessfulGrpcMessageAsync <Empty>().DefaultTimeout();

            response.AssertTrailerStatus();
        }
コード例 #24
0
        public async Task ServerMethodThrowsExceptionWithTrailers_FailureResponse()
        {
            // Arrange
            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, requestMessage);

            // Act
            var response = await Fixture.Client.PostAsync(
                "Greet.Greeter/SayHelloThrowExceptionWithTrailers",
                new StreamContent(ms)).DefaultTimeout();

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            Assert.AreEqual(StatusCode.Unknown.ToTrailerString(), Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.StatusTrailer].Single());
            Assert.AreEqual("User error", Fixture.TrailersContainer.Trailers[GrpcProtocolConstants.MessageTrailer].Single());
            Assert.AreEqual("A value!", Fixture.TrailersContainer.Trailers["test-trailer"].Single());
        }
コード例 #25
0
        public async Task MultipleMessagesFromOneClient_SuccessResponses()
        {
            // Arrange
            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, new ChatMessage
            {
                Name    = "John",
                Message = "Hello Jill"
            });

            var streamingContent = new StreamingContent();
            var httpRequest      = GrpcHttpHelper.Create("Chat.Chatter/Chat");

            httpRequest.Content = streamingContent;

            // Act
            var responseTask = Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);

            // Assert
            Assert.IsFalse(responseTask.IsCompleted, "Server should wait for first message from client");

            var requestStream = await streamingContent.GetRequestStreamAsync().DefaultTimeout();

            await requestStream.WriteAsync(ms.ToArray()).AsTask().DefaultTimeout();

            await requestStream.FlushAsync().DefaultTimeout();

            var response = await responseTask.DefaultTimeout();

            response.AssertIsSuccessfulGrpcRequest();

            var responseStream = await response.Content.ReadAsStreamAsync().DefaultTimeout();

            var pipeReader = PipeReader.Create(responseStream);

            var message1Task = MessageHelpers.AssertReadStreamMessageAsync <ChatMessage>(pipeReader);
            var message1     = await message1Task.DefaultTimeout();

            Assert.AreEqual("John", message1.Name);
            Assert.AreEqual("Hello Jill", message1.Message);

            var message2Task = MessageHelpers.AssertReadStreamMessageAsync <ChatMessage>(pipeReader);

            Assert.IsFalse(message2Task.IsCompleted, "Server is waiting for messages from client");

            ms = new MemoryStream();
            MessageHelpers.WriteMessage(ms, new ChatMessage
            {
                Name    = "Jill",
                Message = "Hello John"
            });

            await requestStream.WriteAsync(ms.ToArray()).AsTask().DefaultTimeout();

            await requestStream.FlushAsync().DefaultTimeout();

            var message2 = await message2Task.DefaultTimeout();

            Assert.AreEqual("Jill", message2.Name);
            Assert.AreEqual("Hello John", message2.Message);

            var finishedTask = MessageHelpers.AssertReadStreamMessageAsync <ChatMessage>(pipeReader);

            Assert.IsFalse(finishedTask.IsCompleted, "Server is waiting for client to end streaming");

            // Complete request stream
            streamingContent.Complete();

            await finishedTask.DefaultTimeout();

            response.AssertTrailerStatus();
        }
コード例 #26
0
        public async Task WriteUntilDeadline_SuccessResponsesStreamed_CoreAsync(ServerStreamingServerMethod <HelloRequest, HelloReply> callHandler)
        {
            // Arrange
            var method = Fixture.DynamicGrpc.AddServerStreamingMethod <HelloRequest, HelloReply>(callHandler);

            var requestMessage = new HelloRequest
            {
                Name = "World"
            };

            var requestStream = new MemoryStream();

            MessageHelpers.WriteMessage(requestStream, requestMessage);

            var httpRequest = GrpcHttpHelper.Create(method.FullName);

            httpRequest.Headers.Add(GrpcProtocolConstants.TimeoutHeader, "200m");
            httpRequest.Content = new GrpcStreamContent(requestStream);

            // Act
            var response = await Fixture.Client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout();

            // Assert
            response.AssertIsSuccessfulGrpcRequest();

            var responseStream = await response.Content.ReadAsStreamAsync().DefaultTimeout();

            var pipeReader = PipeReader.Create(responseStream);

            var messageCount = 0;

            var readTask = Task.Run(async() =>
            {
                while (true)
                {
                    var greeting = await MessageHelpers.AssertReadStreamMessageAsync <HelloReply>(pipeReader).DefaultTimeout();

                    if (greeting != null)
                    {
                        Assert.AreEqual($"How are you World? {messageCount}", greeting.Message);
                        messageCount++;
                    }
                    else
                    {
                        break;
                    }
                }
            });

            await readTask.DefaultTimeout();

            Assert.AreNotEqual(0, messageCount);

            response.AssertTrailerStatus(StatusCode.DeadlineExceeded, "Deadline Exceeded");

            Assert.True(HasLog(LogLevel.Debug, "DeadlineExceeded", "Request with timeout of 00:00:00.2000000 has exceeded its deadline."));

            await TestHelpers.AssertIsTrueRetryAsync(
                () => HasLog(LogLevel.Trace, "DeadlineStopped", "Request deadline stopped."),
                "Missing deadline stopped log.").DefaultTimeout();
        }
コード例 #27
0
        private static void HandleClientDesktopWorker(object token)
        {
            ClientInfo    c      = (ClientInfo)token;
            NetworkStream stream = c.Stream;

            // Let bots know there is a new user
            foreach (dynamic b in Bots)
            {
                b.OnUserConnect(c);
            }

            // Tell all connected clients that we are connected
            Message cm = new Message(c.Name, MessageType.Status);

            cm.SetStatusType(StatusType.Connected);
            SendToAllClients(cm, null, -1);

            Room r = new Room();

            // Put user in none full room
            foreach (KeyValuePair <string, Room> room in Rooms)
            {
                if (!room.Value.AddUser(c))
                {
                    continue;
                }
                else
                {
                    r = room.Value;
                    break;
                }
            }
            if (r.Equals(default(Room)))
            {
                JsonMessage m = new JsonMessage("Server", MessageType.Status);
                m.SetStatusType(StatusType.ErrorDisconnect);
                m.SetContent("All available rooms are full");
                JsonMessageHelpers.SetJsonMessage(stream, m);
                return;
            }

            Message rooms = new Message("Server", MessageType.Request);

            rooms.SetRequestType(RequestType.Rooms);
            rooms.SetContent(Rooms.SerializeRooms());
            MessageHelpers.SetMessage(stream, rooms);

            // Send The Server Message Buffer
            foreach (Message message in r.Buffer)
            {
                MessageHelpers.SetMessage(stream, message);
            }

            while (true)
            {
                try
                {
                    c = clients[c.GUID];
                    Message m = MessageHelpers.GetMessage(stream);
                    foreach (dynamic b in Bots)
                    {
                        m = b.OnMessage(c, m);
                    }

                    // Manage Message buffer
                    if (m.MessageType == MessageType.Message)
                    {
                        r.AddMesssage(m);
                    }
                    else if (m.MessageType == MessageType.Infomation)
                    {
                        MessageHelpers.SetMessage(stream, InformationHandler(m.InfomationType, c.GUID));
                        continue;
                    }
                    else if (m.MessageType == MessageType.Status && m.StatusType == StatusType.ChangeRoom)
                    {
                        try
                        {
                            ClientInfo cInfo = clients[c.GUID];
                            if (!r.AddUser(cInfo))
                            {
                                m = new Message("Server", MessageType.Message);
                                m.SetColor(ColorToNColor(Color.Aquamarine));
                                m.SetContent("The requested room is full");
                                MessageHelpers.SetMessage(stream, m);
                                continue;
                            }
                            r.RemoveUser(cInfo);

                            int id = int.Parse(m.Content);
                            cInfo.SetRoomID(id);
                            clients[c.GUID] = cInfo;
                            Room oldR = r;
                            r = Rooms.Where(x => x.Value.ID == id).First().Value;
                            r.AddUser(cInfo);

                            m = new Message("Server", MessageType.Message);
                            m.SetContent("Moved to Room " + r.Name + "(" + id + ")");
                            MessageHelpers.SetMessage(stream, m);

                            foreach (Message message in r.Buffer)
                            {
                                MessageHelpers.SetMessage(stream, message);
                            }
                            foreach (dynamic b in Bots)
                            {
                                b.OnUserChangeRoom(c, oldR, r);
                            }
                            continue;
                        }
                        catch
                        {
                            try
                            {
                                ClientInfo cInfo = clients[c.GUID];
                                Room       oldR  = r;
                                r = Rooms.Where(x => x.Value.Name == m.Content).First().Value;
                                cInfo.SetRoomID(r.ID);
                                r.AddUser(cInfo);
                                clients[c.GUID] = cInfo;

                                m = new Message("Server", MessageType.Message);
                                m.SetContent("Moved to Room " + r.Name);
                                MessageHelpers.SetMessage(stream, m);

                                foreach (Message message in r.Buffer)
                                {
                                    MessageHelpers.SetMessage(stream, message);
                                }
                                foreach (dynamic b in Bots)
                                {
                                    b.OnUserChangeRoom(c, oldR, r);
                                }
                                continue;
                            }
                            catch { continue; }
                        }
                    }
                    if (m.Name != c.Name)
                    {
                        m.SetName(c.Name);
                    }
                    if (m.StatusType == StatusType.Disconnecting && m.MessageType == MessageType.Status)
                    {
                        foreach (dynamic b in Bots)
                        {
                            b.OnUserDisconnect(c);
                        }
                        r.RemoveUser(clients[c.GUID]);
                        MessageHelpers.SetMessage(stream, m);
                        stream.Close();
                        clients.Remove(c.GUID);

                        Message d = new Message(c.Name, MessageType.Status);
                        d.SetStatusType(StatusType.Disconnected);

                        SendToAllClients(d, null, -1);

                        break;
                    }

                    foreach (KeyValuePair <string, ClientInfo> network in clients)
                    {
                        if (network.Key == c.GUID)
                        {
                            continue;
                        }
                        else
                        {
                            if (m.EndPoint == "")
                            {
                                SendToAllClients(m, null, clients[c.GUID].RoomId, c.GUID);
                                break;
                            }
                            else
                            {
                                if (network.Value.Name == m.EndPoint)
                                {
                                    MessageHelpers.SetMessage(network.Value.Stream, m);
                                }
                            }
                        }
                    }
                }
                catch (IOException)
                {
                    if (clients.ContainsKey(c.GUID))
                    {
                        foreach (dynamic b in Bots)
                        {
                            b.OnUserDisconnect(c);
                        }
                        r.RemoveUser(clients[c.GUID]);
                        clients[c.GUID].Stream.Close();
                        clients.Remove(c.GUID);
                    }
                    foreach (KeyValuePair <string, ClientInfo> network in clients)
                    {
                        Message d = new Message(network.Key == c.Name ? "You" : c.Name, MessageType.Status);
                        d.SetStatusType(StatusType.Disconnected);
                        MessageHelpers.SetMessage(network.Value.Stream, d);
                    }
                    break;
                }
                catch (Exception ex)
                {
                    if (clients.ContainsKey(c.GUID))
                    {
                        foreach (dynamic b in Bots)
                        {
                            b.OnUserDisconnect(c);
                        }
                        r.RemoveUser(clients[c.GUID]);
                        clients[c.GUID].Stream.Close();
                        clients.Remove(c.GUID);
                    }
                    Console.WriteLine(c.Name + " disconnected due to an error. Details: " + ex.Message);
                    foreach (KeyValuePair <string, ClientInfo> network in clients)
                    {
                        Message e = new Message(network.Key == c.Name ? "You" : c.Name, MessageType.Status);
                        e.SetStatusType(StatusType.ErrorDisconnect);
                        MessageHelpers.SetMessage(network.Value.Stream, e);
                    }
                    break;
                }
            }
        }
コード例 #28
0
        public static async void SendToAllClients(Message message, JsonMessage json, int roomID, string sender = "")
        {
            List <Task> tasks = new List <Task>();

            foreach (KeyValuePair <string, ClientInfo> network in clients)
            {
                if (sender != "")
                {
                    if (network.Key == sender)
                    {
                        continue;
                    }
                }
                if (roomID != -1)
                {
                    if (network.Value.RoomId != roomID)
                    {
                        continue;
                    }
                }
                if (message != null)
                {
                    if (message.Name == network.Key)
                    {
                        continue;
                    }
                }
                else
                {
                    if (json.Name == network.Key)
                    {
                        continue;
                    }
                }

                if (network.Value.ClientType == ClientType.Desktop)
                {
                    if (message == null)
                    {
                        tasks.Add(MessageHelpers.SetMessageAsync(network.Value.Stream, json.ToMessage()));
                    }
                    else
                    {
                        tasks.Add(MessageHelpers.SetMessageAsync(network.Value.Stream, message));
                    }
                }
                else if (network.Value.ClientType == ClientType.Web)
                {
                    if (json == null)
                    {
                        tasks.Add(JsonMessageHelpers.SetJsonMessageAsync(network.Value.Stream, message.ToJsonMessage()));
                    }
                    else
                    {
                        tasks.Add(JsonMessageHelpers.SetJsonMessageAsync(network.Value.Stream, json));
                    }
                }
                else
                {
                    Console.WriteLine("Unknown Client");
                }
            }

            while (tasks.Any())
            {
                tasks.Remove(await Task.WhenAny(tasks));
            }
        }
コード例 #29
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;

            // Strip out all mentions.  As all channel messages to a bot must @mention the bot itself, you must strip out the bot name at minimum.
            // This uses the extension SDK function GetTextWithoutMentions() to strip out ALL mentions
            var text = activity.GetTextWithoutMentions();

            if (text == null && (activity.Attachments != null && activity.Attachments.Count == 0))
            {
                // if the activity is not a system event, and it does not have text or attachment, treat it as a SubmitAction
                //await HandleSubmitAction(context, activity);
            }
            else
            {
                #region Receive file
                // If a file was sent, echo back its name try to read it.
                if (activity.Attachments != null && activity.Attachments.Count > 0)
                {
                    foreach (var attachment in activity.Attachments)
                    {
                        if (attachment.ContentType == FileDownloadInfo.ContentType)
                        {
                            await context.PostAsync($"Received a file named {attachment.Name}");

                            await FileHelpers.ProcessAttachment(attachment, context);
                        }
                    }
                }
                #endregion

                if (!String.IsNullOrEmpty(text))
                {
                    // Check for suppported commands
                    // This simple text parsing assumes the command is the first two tokens,
                    // and parameters are the remainder.
                    var split = text.Split(' ');
                    // The user is asking for one of the supported commands.
                    if (split.Length >= 2)
                    {
                        var cmd      = split[0].ToLower();
                        var keywords = split.Skip(1).ToArray();

                        #region Commands

                        if (cmd.Contains("resume"))
                        {
                            // Return "resume file" for the given candidate name.
                            await HandleResumeCommand(context, keywords);
                        }
                        else if (cmd.Contains("schedule"))
                        {
                            await CommandHandlers.HandleScheduleCommand(context, activity, keywords);
                        }
                        else if (cmd.Contains("open"))
                        {
                            await CommandHandlers.HandleOpenCommand(context);
                        }
                        else if (cmd.Contains("candidate"))
                        {
                            await CommandHandlers.HandleCandidateCommand(context, activity, keywords);
                        }
                        else if (cmd.Contains("new"))
                        {
                            await CommandHandlers.HandleNewCommand(context);
                        }
                        else if (cmd.Contains("assign"))
                        {
                            await CommandHandlers.HandleAssignCommand(context, split);
                        }

                        #endregion
                    }
                    else if (text.Contains("help"))
                    {
                        // Respond with standard help message.
                        await MessageHelpers.SendMessage(context, MessageHelpers.CreateHelpMessage("Sure, I can provide help info about me."));
                    }
                    else if (text.Contains("welcome") || text.Contains("hello") || text.Contains("hi"))
                    {
                        await MessageHelpers.SendMessage(context, MessageHelpers.CreateHelpMessage("## Welcome to the Contoso Talent Management app"));
                    }
                    else
                    // Don't know what to say so this is the generic handling here.
                    {
                        await MessageHelpers.SendMessage(context, MessageHelpers.CreateHelpMessage("I'm sorry, I did not understand you :("));
                    }
                }
            }
            context.Wait(MessageReceivedAsync);
        }
コード例 #30
0
        public async Task SendCompressedMessage_ServerStreamingEnabledInCall_CompressedMessageReturned()
        {
            async Task ServerStreamingEnableCompression(HelloRequest request, IServerStreamWriter <HelloReply> responseStream, ServerCallContext context)
            {
                var headers = new Metadata {
                    new Metadata.Entry("grpc-internal-encoding-request", "gzip")
                };
                await context.WriteResponseHeadersAsync(headers);

                await responseStream.WriteAsync(new HelloReply { Message = "Hello 1" });

                responseStream.WriteOptions = new WriteOptions(WriteFlags.NoCompress);
                await responseStream.WriteAsync(new HelloReply { Message = "Hello 2" });
            }

            // Arrange
            var method = Fixture.DynamicGrpc.AddServerStreamingMethod <HelloRequest, HelloReply>(ServerStreamingEnableCompression);

            var ms = new MemoryStream();

            MessageHelpers.WriteMessage(ms, new HelloRequest
            {
                Name = "World"
            });

            var httpRequest = GrpcHttpHelper.Create(method.FullName);

            httpRequest.Content = new PushStreamContent(
                async s =>
            {
                await s.WriteAsync(ms.ToArray()).AsTask().DefaultTimeout();
                await s.FlushAsync().DefaultTimeout();
            });

            // Act
            var responseTask = Fixture.Client.SendAsync(httpRequest);

            // Assert
            var response = await responseTask.DefaultTimeout();

            response.AssertIsSuccessfulGrpcRequest();

            Assert.AreEqual("gzip", response.Headers.GetValues("grpc-encoding").Single());

            var responseStream = await response.Content.ReadAsStreamAsync().DefaultTimeout();

            var pipeReader = PipeReader.Create(responseStream);

            ReadResult readResult;

            readResult = await pipeReader.ReadAsync();

            Assert.AreEqual(1, readResult.Buffer.FirstSpan[0]); // Message is compressed
            var greeting1 = await MessageHelpers.AssertReadStreamMessageAsync <HelloReply>(pipeReader, "gzip").DefaultTimeout();

            Assert.AreEqual($"Hello 1", greeting1.Message);

            readResult = await pipeReader.ReadAsync();

            Assert.AreEqual(0, readResult.Buffer.FirstSpan[0]); // Message is uncompressed
            var greeting2 = await MessageHelpers.AssertReadStreamMessageAsync <HelloReply>(pipeReader, "gzip").DefaultTimeout();

            Assert.AreEqual($"Hello 2", greeting2.Message);

            var finishedTask = MessageHelpers.AssertReadStreamMessageAsync <HelloReply>(pipeReader);

            Assert.IsNull(await finishedTask.DefaultTimeout());
        }