public void Setup()
        {
            _requestClient = new MessageRequestClient<PingMessage, PongMessage>(Bus, InputQueueAddress, TimeSpan.FromSeconds(8),
                TimeSpan.FromSeconds(8));

            _response = _requestClient.Request(new PingMessage());
        }
 private static async Task<string> GetCustomerName(IRequestClient<ISimpleRequest, ISimpleResponse> client, string customerId)
 {
     Console.WriteLine($"async call on thread {Thread.CurrentThread.ManagedThreadId}");
     ISimpleResponse response = await client.Request(new SimpleRequest(customerId));
     Console.WriteLine("client response received");
     return response.CusomerName;
     
 }
        internal static IServerDensityApi Initialise(ServerDensitySettings settings, IRequestClient requestClient)
        {
            if (string.IsNullOrEmpty(settings.ApiKey))
                throw new ArgumentException("Api key missing. Api key is required to initialise API");

            if (settings.Credentials == null || string.IsNullOrEmpty(settings.Credentials.UserName) || string.IsNullOrEmpty(settings.Credentials.Password))
                throw new ArgumentException("Credetials are required for the api calls to function correctly.");

            if (string.IsNullOrEmpty(settings.Account))
                throw new ArgumentException("Account missing. Account is required to initialise API. It will be in the form of [name].serverdensity.com");

            return new ServerDensityApi(settings) { RequestClient = requestClient ?? new RequestClient(settings.Credentials) };
        }
Exemple #4
0
	    public Trello(INetworkService networkService, IRequestClient client)
		{
		    _networkService = networkService;
		    _client = client;

		    Members = new AsyncMembers(_client);
            Boards = new AsyncBoards(_client);
            Lists = new AsyncLists(_client);
            Cards = new AsyncCards(_client);
            Checklists = new AsyncChecklists(_client);
            Organizations = new AsyncOrganizations(_client);
            Notifications = new AsyncNotifications(_client);
            Tokens = new AsyncTokens(_client);
            Actions = new AsyncActions(_client);
		}
        public async Task Should_get_the_job_accepted()
        {
            var serviceClient = Bus.CreateServiceClient();

            IRequestClient <SubmitJob <CrunchTheNumbers> > requestClient = serviceClient.CreateRequestClient <SubmitJob <CrunchTheNumbers> >();

            for (var i = 0; i < Count; i++)
            {
                Response <JobSubmissionAccepted> response = await requestClient.GetResponse <JobSubmissionAccepted>(new
                {
                    JobId = _jobIds[i],
                    Job   = new { Duration = TimeSpan.FromSeconds(1) }
                });
            }

            ConsumeContext <JobCompleted>[] completed = await Task.WhenAll(_completed.Select(x => x.Task));
        }
Exemple #6
0
 public CreateNewsCommand(
     INewsRepository repository,
     IDbNewsMapper mapper,
     ICreateNewsRequestValidator validator,
     IAccessValidator accessValidator,
     IHttpContextAccessor httpContextAccessor,
     IRequestClient <ICreateDepartmentEntityRequest> rcCreateDepartmentEntity,
     ILogger <CreateNewsCommand> logger)
 {
     _repository               = repository;
     _mapper                   = mapper;
     _validator                = validator;
     _accessValidator          = accessValidator;
     _httpContextAccessor      = httpContextAccessor;
     _rcCreateDepartmentEntity = rcCreateDepartmentEntity;
     _logger                   = logger;
 }
        // Attempts to load the entry point resource and resets the lazy loaded state if there
        // is an exception so future attempts can be made.
        private async Task <HalEntryPointResource> GetEntryPointResource(IRequestClient requestClient)
        {
            try
            {
                var request  = ApiRequest.Get(_entryPointPath);
                var response = await requestClient.SendAsync <HalEntryPointResource>(request).ConfigureAwait(false);

                response.ThrowIfNotSuccessStatusCode();
                return(response.Content);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error loading service entry resource");
                _apiEntryPointLazy = new Lazy <Task <HalEntryPointResource> >(() => GetEntryPointResource(requestClient), true);
                throw;
            }
        }
        public async Task Should_receive_the_response()
        {
            IRequestClient <InitialRequest> client = RequestClient;

            _correlationId = NewId.NextGuid();

            Response <InitialResponse> response = await client.GetResponse <InitialResponse>(new
            {
                CorrelationId = _correlationId,
                Value         = "World"
            });

            Assert.That(response.Message.Value, Is.EqualTo("Hello, World"));
            Assert.That(response.ConversationId.Value, Is.EqualTo(response.Message.OriginalConversationId));
            Assert.That(response.InitiatorId.Value, Is.EqualTo(_correlationId));
            Assert.That(response.Message.OriginalInitiatorId, Is.EqualTo(_correlationId));
        }
        public async Task Should_get_the_job_accepted()
        {
            var serviceClient = Bus.CreateServiceClient();

            IRequestClient <SubmitJob <CrunchTheNumbers> > requestClient = serviceClient.CreateRequestClient <SubmitJob <CrunchTheNumbers> >();

            Response <JobSubmissionAccepted> response = await requestClient.GetResponse <JobSubmissionAccepted>(new
            {
                JobId = _jobId,
                Job   = new { Duration = TimeSpan.FromSeconds(1) }
            });

            Assert.That(response.Message.JobId, Is.EqualTo(_jobId));

            // just to capture all the test output in a single window
            ConsumeContext <JobCompleted> completed = await _completed;
        }
Exemple #10
0
        public async Task Should_be_awesome_with_a_side_of_sourdough_toast()
        {
            IRequestClient <GetValue> client = Bus.CreateRequestClient <GetValue>(InputQueueAddress);

            Response <Value> response;

            using (RequestHandle <GetValue> request = client.Create(new GetValue()))
            {
                request.UseExecute(context => context.Headers.Set("Frank", "Mary"));

                response = await request.GetResponse <Value>();
            }

            Assert.That(response.RequestId.HasValue, Is.True);
            Assert.That(response.Headers.TryGetHeader("Frank", out var value), Is.True);
            Assert.That(value, Is.EqualTo("Mary"));
        }
        public static Request RequestClient(
            this Request request,
            IRequestClient requestClient)
        {
            request = request ?? Request.Default;

            var services = request.Services;

            return(request.Services(new RequestServices(
                                        requestClient: requestClient,
                                        authorizationStrategy: services.AuthorizationStrategy,
                                        retryStrategy: services.RetryStrategy,
                                        requestSerializer: services.RequestSerializer,
                                        responseDeserializer: services.ResponseDeserializer,
                                        beforeRequestHandlers: services.BeforeRequestHandlers,
                                        beforeRetryHandlers: services.BeforeRetryHandlers,
                                        afterResponseHandlers: services.AfterResponseHandlers)));
        }
Exemple #12
0
 public UsersController(IPublishEndpoint publishEndpoint,
                        IRequestClient <GetUserContactsRequestDto, GetUserContactsResponseDto> getUserContactsClient,
                        IRequestClient <GetUserProfileDataRequestDto, GetUserProfileDataResponseDto> getUserProfileDataClient,
                        IRequestClient <RegisterUserRequestDto, RegisterUserResponseDto> registerUserClient,
                        IRequestClient <VerifyRegisterUserRequestDto, VerifyRegisterUserResponseDto> verifyRegisterUserClient,
                        IRequestClient <UserSignInRequestDto, UserSignInResponseDto> userSignInClient,
                        IRequestClient <UpdateUserProfileDataRequestDto, UpdateUserProfileDataResponseDto> updateUserProfileDataClient,
                        Policy policy)
 {
     this._publishEndpoint             = publishEndpoint;
     this._getUserContactsClient       = getUserContactsClient;
     this._getUserProfileDataClient    = getUserProfileDataClient;
     this._registerUserClient          = registerUserClient;
     this._verifyRegisterUserClient    = verifyRegisterUserClient;
     this._userSignInClient            = userSignInClient;
     this._updateUserProfileDataClient = updateUserProfileDataClient;
     this._policy = policy;
 }
            public async Task Should_match_an_existing_instance()
            {
                IRequestClient <Start> startClient = Bus.CreateRequestClient <Start>(InputQueueAddress, TestTimeout);

                await startClient.GetResponse <StartupComplete>(new Start("A", NewId.NextGuid()));

                IRequestClient <CheckStatus> statusClient = Bus.CreateRequestClient <CheckStatus>(InputQueueAddress, TestTimeout);

                (var status, var notFound) = await statusClient.GetResponse <Status, InstanceNotFound>(new CheckStatus("A"), TestCancellationToken);

                Assert.That(status.IsCompletedSuccessfully(), Is.True);

                MassTransit.Response <Status> result = await status;

                Assert.AreEqual("A", result.Message.ServiceName);

                Assert.That(async() => await notFound, Throws.TypeOf <TaskCanceledException>());
            }
Exemple #14
0
            public async Task Should_not_update_the_saga_repository()
            {
                var serviceId = NewId.NextGuid();

                IRequestClient <Start> startClient = Bus.CreateRequestClient <Start>(InputQueueAddress, TestTimeout);

                await startClient.GetResponse <StartupComplete>(new Start { CorrelationId = serviceId }, TestCancellationToken);

                IRequestClient <CheckStatus> requestClient = Bus.CreateRequestClient <CheckStatus>(InputQueueAddress, TestTimeout);

                Response <Status> status = await requestClient.GetResponse <Status>(new CheckStatus { CorrelationId = serviceId }, TestCancellationToken);

                Assert.That(status.Message.StatusText, Is.EqualTo("Started"));

                status = await requestClient.GetResponse <Status>(new CheckStatus { CorrelationId = serviceId }, TestCancellationToken);

                Assert.That(status.Message.StatusText, Is.EqualTo("Started"));
            }
Exemple #15
0
        /// <summary>
        /// Send a request from the bus to the endpoint, and return a Task which can be awaited for the response.
        /// </summary>
        /// <param name="bus">A started bus instance</param>
        /// <param name="message">The request message</param>
        /// <param name="cancellationToken">An optional cancellationToken for this request</param>
        /// <param name="timeout">An optional timeout for the request (defaults to 30 seconds)</param>
        /// <param name="callback">A callback, which can modify the <see cref="SendContext" /> of the request</param>
        /// <typeparam name="TRequest">The request type</typeparam>
        /// <typeparam name="TResponse">The response type</typeparam>
        /// <returns></returns>
        public static async Task <Response <TResponse> > Request <TRequest, TResponse>(this IBus bus, TRequest message,
                                                                                       CancellationToken cancellationToken = default,
                                                                                       RequestTimeout timeout = default, Action <SendContext <TRequest> > callback = null)
            where TRequest : class
            where TResponse : class
        {
            IRequestClient <TRequest> requestClient = bus.CreateRequestClient <TRequest>(timeout);

            using (RequestHandle <TRequest> requestHandle = requestClient.Create(message, cancellationToken))
            {
                if (callback != null)
                {
                    requestHandle.UseExecute(callback);
                }

                return(await requestHandle.GetResponse <TResponse>().ConfigureAwait(false));
            }
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="AccessRightsConsumer" /> class.
        /// </summary>
        /// <param name="findUserRequest">The find user request.</param>
        /// <param name="findUserGroupRequest">The find user group request.</param>
        /// <param name="listUsersInGroupRequest">The list users in group request.</param>
        /// <param name="accessRightsManager">The access rights service.</param>
        /// <param name="databaseContext">The database context.</param>
        public AccessRightsConsumer(IRequestClient <IFindUserByName, IFindUserByNameResult> findUserRequest,
                                    IRequestClient <IFindUserGroupByName, IFindUserGroupByNameResult> findUserGroupRequest,
                                    IRequestClient <IListUsersInGroup, IListUsersInGroupResult> listUsersInGroupRequest,
                                    IAccessRightsManager accessRightsManager,
                                    IDatabaseContext databaseContext)
        {
            Contract.Requires(findUserRequest != null);
            Contract.Requires(findUserGroupRequest != null);
            Contract.Requires(listUsersInGroupRequest != null);
            Contract.Requires(accessRightsManager != null);
            Contract.Requires(databaseContext != null);

            _findUserRequest         = findUserRequest;
            _findUserGroupRequest    = findUserGroupRequest;
            _listUsersInGroupRequest = listUsersInGroupRequest;
            _accessRightsManager     = accessRightsManager;
            _databaseContext         = databaseContext;
        }
        public AccessRightsController(IRequestClient <IListAccessRights, IListAccessRightsResult> listAccessRightsRequest,
                                      IRequestClient <IListAccessPoints, IListAccessPointsResult> listAccessPointsRequest,
                                      IRequestClient <IListUsers, IListUsersResult> listUsersRequest,
                                      IRequestClient <IListUserGroups, IListUserGroupsResult> listUserGroupsRequest,
                                      IAccessRightsService accessRightsService)
        {
            Contract.Requires(listAccessRightsRequest != null);
            Contract.Requires(listAccessPointsRequest != null);
            Contract.Requires(listUsersRequest != null);
            Contract.Requires(listUserGroupsRequest != null);
            Contract.Requires(accessRightsService != null);

            _listAccessRightsRequest = listAccessRightsRequest;
            _listAccessPointsRequest = listAccessPointsRequest;
            _listUsersRequest        = listUsersRequest;
            _listUserGroupsRequest   = listUserGroupsRequest;
            _accessRightsService     = accessRightsService;
        }
Exemple #18
0
        public async Task <OperationResult <BookResponse> > DeleteBook(
            [FromServices] IRequestClient <BookRequest> client,
            [FromServices] IRabbitRequestCommand <BookResponse, BookRequest> command,
            [FromQuery] int id)
        {
            var request = new BookRequest()
            {
                Id = id, Mode = RequestMode.Delete
            };

            var result = await command.Execute(client, request);

            foreach (var it in result.ErrorMessages)
            {
                _logger.Log(LogLevel.Error, it);
            }
            return(result);
        }
        static void Main()
        {
            //ConfigureLogger();

            // MassTransit to use Log4Net
            //Log4NetLogger.Use();

            IBusControl busControl = CreateBus();

            TaskUtil.Await(() => busControl.StartAsync());

            try
            {
                IRequestClient <ISubmitOrder, IOrderReceived> client = CreateRequestClient(busControl);

                for (; ;)
                {
                    Console.Write("Enter customer id (quit exits): ");
                    string customerId = Console.ReadLine();
                    if (customerId == "quit")
                    {
                        break;
                    }

                    // this is run as a Task to avoid weird console application issues
                    Task.Run(async() =>
                    {
                        IOrderReceived response = await client.Request(new SubmitOrder {
                            OrderNumber = customerId
                        });

                        Console.WriteLine("Customer Name: {0}", response.OrderNumber + ": Name");
                    }).Wait();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception!!! OMG!!! {0}", ex);
            }
            finally
            {
                busControl.Stop();
            }
        }
Exemple #20
0
 public AccountCommandHandler(IAccountInfoRepository rep,
                              IUserIdGenRepository genRepository,
                              IAccountRedisRepository redis,
                              IMediatorHandler bus,
                              IMapper mapper,
                              IRequestClient <GetMoneyMqCommand> moneyClient,
                              WSHostManager hostManager, InitRewardInfo initRewardInfo,
                              IRequestClient <AddMoneyMqCommand> moneyAddClient)
 {
     _accountRepository = rep;
     _genRepository     = genRepository;
     _redis             = redis;
     _bus            = bus;
     _mapper         = mapper;
     _moneyClient    = moneyClient;
     _hostManager    = hostManager;
     _initRewardInfo = initRewardInfo;
     _moneyAddClient = moneyAddClient;
 }
        public async Task Should_schedule_the_message_and_redeliver_to_the_instance()
        {
            IRequestClient <CheckStatus> requestClient = Bus.CreateRequestClient <CheckStatus>(InputQueueAddress, TestTimeout);
            var response = requestClient.GetResponse <Status, InstanceNotFound>(new CheckStatus("A"), TestCancellationToken);

            await Task.Delay(500);

            var message = new Start("A", NewId.NextGuid());

            await InputQueueSendEndpoint.Send(message);

            var(status, notFound) = await response;

            Assert.That(async() => await notFound, Throws.TypeOf <TaskCanceledException>());

            await status;

            Assert.AreEqual("A", status.Result.Message.ServiceName);
        }
Exemple #22
0
        static void Main(string[] args)
        {
            var bus = Bus.Factory.CreateUsingRabbitMq(sbc =>
            {
                var host = sbc.Host(new Uri("rabbitmq://localhost"), h =>
                {
                    h.Username("guest");
                    h.Password("guest");
                });
            });


            bus.Start();

            //bus.Publish(new YourMessage { Text = "Hi" });

            var serviceAddress = new Uri("rabbitmq://localhost/request_service");
            IRequestClient <ICheckOrderStatus, IOrderStatusResult> client =
                bus.CreateRequestClient <ICheckOrderStatus, IOrderStatusResult>(serviceAddress, TimeSpan.FromSeconds(10));

            Task.Run(async() =>
            {
                var tasks = new List <Task>();
                for (var i = 0; i < 30; i++)
                {
                    Task.Factory.StartNew(async() =>
                    {
                        var a = await client.Request(new CheckOrderStatus("1"));
                        File.WriteAllText(@"F:\" + Guid.NewGuid().ToString("N") + "___" + a.StatusText + ".txt",
                                          a.StatusText);
                    });
                }

                await Task.Delay(100000);
            }).Wait();



            Console.WriteLine("Press any key to exit");
            Console.ReadKey();

            bus.Stop();
        }
Exemple #23
0
        public async Task Should_fault_if_clientId_is_not_specified()
        {
            Task <ConsumeContext <Up <DeployPayload> > > upHandler = SubscribeHandler <Up <DeployPayload> >();

            var clientId = NewId.NextGuid();

            await Bus.Publish <Link <DeployPayload> >(new
            {
                __ResponseAddress = Bus.Address,
                __TimeToLive      = 10000,
                ClientId          = clientId
            });

            ConsumeContext <Up <DeployPayload> > upContext = await upHandler;

            IRequestClient <DeployPayload> client = Bus.CreateRequestClient <DeployPayload>(upContext.Message.Service.ServiceAddress);

            Assert.That(async() => await client.GetResponse <PayloadDeployed>(new { Target = "Bogey" }), Throws.TypeOf <RequestFaultException>());
        }
Exemple #24
0
 public CreateUserRightsCommand(
     IUserRepository repository,
     IRightsIdsValidator validator,
     IAccessValidator accessValidator,
     IResponseCreator responseCreator,
     IRequestClient <ICheckUsersExistence> rcCheckUser,
     ILogger <CreateUserRightsCommand> logger,
     IHttpContextAccessor httpContextAccessor,
     IMemoryCache cache)
 {
     _repository          = repository;
     _validator           = validator;
     _accessValidator     = accessValidator;
     _responseCreator     = responseCreator;
     _rcCheckUser         = rcCheckUser;
     _logger              = logger;
     _httpContextAccessor = httpContextAccessor;
     _cache = cache;
 }
Exemple #25
0
        private async Task <MonitoringResult> TestAbbyyLicence(
            IRequestClient <DocumentConverterInfoRequest, DocumentConverterInfoResponse> requestClient)
        {
            var watch = new Stopwatch();
            MonitoringResult result;

            try
            {
                watch.Start();
                var infoResponse = await requestClient.Request(new DocumentConverterInfoRequest());

                watch.Stop();

                result = new MonitoringResult
                {
                    MonitoredServices = "Abbyy Licence",
                    Status            = infoResponse.PagesRemaining > 0 ? HeartbeatStatus.Ok.ToString() : HeartbeatStatus.Nok.ToString(),
                    ExecutionTime     = watch.ElapsedMilliseconds
                };

                if (infoResponse.PagesRemaining == null)
                {
                    result.Message = "Nok, Information missing. Abbyy not installed?";
                }
                else
                {
                    result.Message  = infoResponse.PagesRemaining > 0 ? "Ok" : "Nok";
                    result.Message += $", Remaining pages: {infoResponse.PagesRemaining}";
                }
            }
            catch (Exception ex)
            {
                result = new MonitoringResult
                {
                    MonitoredServices = "Abbyy Licence",
                    Status            = HeartbeatStatus.Nok.ToString(),
                    Message           = $"Viaduc service call failed. Exception: {ex.Message}",
                    ExecutionTime     = watch.ElapsedMilliseconds
                };
            }

            return(result);
        }
 public FindRolesCommand(
     ILogger <FindRolesCommand> logger,
     IRoleRepository roleRepository,
     IUserInfoMapper userInfoMapper,
     IRoleInfoMapper roleInfoMapper,
     IRightInfoMapper rightMapper,
     IRequestClient <IGetUsersDataRequest> usersDataRequestClient,
     IBaseFindFilterValidator findFilterValidator,
     IHttpContextAccessor httpContextAccessor)
 {
     _logger                 = logger;
     _roleRepository         = roleRepository;
     _roleInfoMapper         = roleInfoMapper;
     _userInfoMapper         = userInfoMapper;
     _rightMapper            = rightMapper;
     _usersDataRequestClient = usersDataRequestClient;
     _findFilterValidator    = findFilterValidator;
     _httpContextAccessor    = httpContextAccessor;
 }
Exemple #27
0
        public async void AddMoney()
        {
            IRequestClient <AddMoneyMqCommand> client = _mqBus.CreateRequestClient <AddMoneyMqCommand>
                                                            (new Uri("rabbitmq://localhost/SkyWatch/Money"));
            IRequestClient <GetMoneyMqCommand> getClient = _mqBus.CreateRequestClient <GetMoneyMqCommand>
                                                               (new Uri("rabbitmq://localhost/SkyWatch/Money"));
            var getResponse = getClient.GetResponseExt <GetMoneyMqCommand, BodyResponse <MoneyMqResponse> >(new GetMoneyMqCommand(10000000002));

            getResponse.Wait();
            _testOutputHelper.WriteLine($"GetMoney:{getResponse.Result.Message.Body.CurCoins} --02");
            await client.GetResponseExt <AddMoneyMqCommand, BodyResponse <MoneyMqResponse> >(new AddMoneyMqCommand(10000000002, 10000000, 0, 0));

            Assert.Equal(StatusCodeDefines.Success, getResponse.Result.Message.StatusCode);

            /*for (int i = 0; i < 36000000; ++i)
             * {
             *  await client.GetResponseExt<AddMoneyMqCommand, BodyResponse<MoneyMqResponse>>(new AddMoneyMqCommand(10000000002, 10000, 10000));
             *  await client.GetResponseExt<AddMoneyMqCommand, BodyResponse<MoneyMqResponse>>(new AddMoneyMqCommand(10000000002, -10000, -10000));
             *  _testOutputHelper.WriteLine($"GetMoney.....");
             *  Thread.Sleep(1);
             *  //var response1 = _mqBus.Publish(new AddMoneyMqCommand(10000000002, 10000, 10000));
             *  //var response2 = _mqBus.Publish(new AddMoneyMqCommand(10000000002, -10000, -10000));
             *
             *  /*Assert.Equal(StatusCodeDefines.Success, moneyRes.Message.StatusCode);
             *  Assert.Equal(moneyResponse.Body.CurCoins + 10000, response.Result.Message.Body.CurCoins);
             *  Assert.Equal(moneyResponse.Body.Carry + 10000, response.Result.Message.Body.Carry);
             *
             *  Assert.Equal(StatusCodeDefines.Success, moneyRes.Message.StatusCode);
             *  Assert.Equal(moneyResponse.Body.CurCoins, moneyRes.Message.Body.CurCoins);
             *  Assert.Equal(moneyResponse.Body.Carry, moneyRes.Message.Body.Carry);
             * }*/


            /*var getResponse2 = getClient.GetResponseExt<GetMoneyMqCommand, BodyResponse<MoneyMqResponse>>(new GetMoneyMqCommand(10000000002));
             * await getResponse2;
             * _testOutputHelper.WriteLine($"GetMoney:{getResponse2.Result.Message.Body.CurCoins} --03");
             * Assert.Equal(StatusCodeDefines.Success, getResponse2.Result.Message.StatusCode);
             * Assert.Equal(80000, getResponse2.Result.Message.Body.CurCoins);
             * Assert.Equal(80000, getResponse2.Result.Message.Body.Carry);
             * Assert.Equal(getResponse.Result.Message.Body.CurCoins, getResponse2.Result.Message.Body.CurCoins);
             * Assert.Equal(getResponse.Result.Message.Body.Carry, getResponse2.Result.Message.Body.Carry);*/
        }
Exemple #28
0
        private async Task <MonitoringResult> TestAisDb(IRequestClient <AisDbCheckRequest, AisDbCheckResponse> requestClient)
        {
            var watch = new Stopwatch();
            MonitoringResult result;

            try
            {
                watch.Start();
                var response = await requestClient.Request(new AisDbCheckRequest());

                watch.Stop();

                result = new MonitoringResult
                {
                    MonitoredServices = "AIS DB",
                    ExecutionTime     = watch.ElapsedMilliseconds
                };

                if (response.Ok)
                {
                    result.Status  = HeartbeatStatus.Ok.ToString();
                    result.Message = $"Ok, DB Version = {response.DbVersion}";
                }
                else
                {
                    result.Status  = HeartbeatStatus.Nok.ToString();
                    result.Message = $"Nok, Exception: {response.Exception.Message}";
                }
            }
            catch (Exception ex)
            {
                result = new MonitoringResult
                {
                    MonitoredServices = "AIS DB",
                    Status            = HeartbeatStatus.Nok.ToString(),
                    Message           = $"Viaduc service call failed which execute the test. Exception: {ex.Message}",
                    ExecutionTime     = watch.ElapsedMilliseconds
                };
            }

            return(result);
        }
        static void Main()
        {
            ConfigureLogger();

            // MassTransit to use Log4Net
            Log4NetLogger.Use();

            IBusControl busControl = CreateBus();

            busControl.Start();

            try
            {
                IRequestClient <ISimpleRequest, ISimpleResponse> client = CreateRequestClient(busControl);

                for (;;)
                {
                    Console.Write("Enter customer id (quit exits): ");
                    string customerId = Console.ReadLine();
                    if (customerId == "quit")
                    {
                        break;
                    }

                    // this is run as a Task to avoid weird console application issues
                    Task.Run(async() =>
                    {
                        ISimpleResponse response = await client.Request(new SimpleRequest(customerId));

                        Console.WriteLine("Customer Name: {0}", response.CusomerName);
                    }).Wait();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception!!! OMG!!! {0}", ex);
            }
            finally
            {
                busControl.Stop();
            }
        }
        static void Main()
        {
            ConfigureLogger();

            Log4NetLogger.Use();

            IBusControl busControl = CreateBus();

            try
            {
                TaskUtil.Await(() => busControl.StartAsync());

                IRequestClient <ISimpleRequest, ISimpleResponse> client = busControl.CreateRequestClient();

                for (;;)
                {
                    Console.Write("Enter customer id (quit exits): ");
                    string customerId = Console.ReadLine();
                    if (customerId == "quit")
                    {
                        break;
                    }

                    Task.Run(async() =>
                    {
                        var response = await client.Request(new SimpleRequest(customerId));

                        Console.WriteLine("Customer Name: {0}", response.CusomerName);
                    }).Wait();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                busControl.Stop();
            }

            Console.ReadLine();
        }
Exemple #31
0
        public async Task <IResponseContractData> PostAsync(IRequestContractData contractDataRequest)
        {
            logger.LogInformation("SendDataProcess.PostAsync has been called");

            try
            {
                IRequestClient <IRequestContractData, IResponseContractData> client = bus.CreateRequestClient <IRequestContractData, IResponseContractData>(new Uri($"{serviceBusSettings.Url}{serviceBusSettings.Queue}"), TimeSpan.FromSeconds(15));

                var responseContractData = await client.Request(contractDataRequest);

                logger.LogInformation($"Received response: {responseContractData.AsString()}");

                return(responseContractData);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message + "\n" + ex.InnerException?.ToString());
                throw ex;
            }
        }
Exemple #32
0
        public async Task Link(CancellationToken cancellationToken)
        {
            LogContext.Debug?.Log("Linking: {ClientId} {MessageType}", ClientId, TypeMetadataCache <TMessage> .ShortName);

            IRequestClient <Link <TMessage> > client = _clientFactory.CreateRequestClient <Link <TMessage> >();

            Response <Up <TMessage> > response = await client.GetResponse <Up <TMessage> >(new { ClientId }, cancellationToken).ConfigureAwait(false);

            var serviceAddress = response.Message.Service.ServiceAddress;

            var instance = response.Message.Instance;

            var instanceContext = await _instanceCache.GetOrAdd(instance.InstanceId, instance).ConfigureAwait(false);

            _distribution.Add(instanceContext);

            LogContext.Debug?.Log("Linked: {ClientId} {MessageType} {ServiceAddress}", ClientId, TypeMetadataCache <TMessage> .ShortName, serviceAddress);

            _serviceAddress.TrySetResult(serviceAddress);
        }
        public async Task Using_DI_should_not_timeout()
        {
            var provider = new ServiceCollection()
                           .AddMassTransitInMemoryTestHarness(cfg =>
            {
                cfg.AddSagaStateMachine <TestSagaStateMachine, TestSaga>()
                .InMemoryRepository();

                cfg.AddSagaStateMachineTestHarness <TestSagaStateMachine, TestSaga>();
                cfg.AddPublishMessageScheduler();
                cfg.AddRequestClient <StartCommand>();
            })
                           .BuildServiceProvider(true);

            var harness = provider.GetRequiredService <InMemoryTestHarness>();

            harness.TestTimeout     = TimeSpan.FromSeconds(15);
            harness.OnConfigureBus += x => BusTestFixture.ConfigureBusDiagnostics(x);
            await harness.Start();

            // Act
            try
            {
                using var scope = provider.CreateScope();
                IRequestClient <StartCommand>   client   = scope.ServiceProvider.GetRequiredService <IRequestClient <StartCommand> >();
                Response <StartCommandResponse> response = await client.GetResponse <StartCommandResponse>(
                    new
                {
                    CorrelationId = InVar.Id,
                });

                // Assert
                // did the actual saga consume the message
                var sagaHarness = provider.GetRequiredService <IStateMachineSagaTestHarness <TestSaga, TestSagaStateMachine> >();
                Assert.True(await sagaHarness.Consumed.Any <StartCommand>());
            }
            finally
            {
                await harness.Stop();
            }
        }
        public async Task Should_get_the_job_accepted()
        {
            IRequestClient <SubmitJob <GrindTheGears> > requestClient = Bus.CreateRequestClient <SubmitJob <GrindTheGears> >();

            Response <JobSubmissionAccepted> response = await requestClient.GetResponse <JobSubmissionAccepted>(new
            {
                JobId = _jobId,
                Job   = new
                {
                    GearId   = _jobId,
                    Duration = TimeSpan.FromSeconds(1)
                }
            });

            Assert.That(response.Message.JobId, Is.EqualTo(_jobId));

            // just to capture all the test output in a single window
            ConsumeContext <JobFaulted> faulted = await _faulted;

            await _fault;
        }
 public void Setup()
 {
     _requestClient = new MessageRequestClient<PingMessage, PongMessage>(SecondBus, InputQueueAddress, TestTimeout);
 }
 public void Setup()
 {
     _requestClient = new MessageRequestClient<PingMessage, PongMessage>(Bus, _serviceAddress, TestTimeout);
 }
        public void Run(CancellationToken cancellationToken = default(CancellationToken))
        {
            _capture = new MessageMetricCapture(_settings.MessageCount);

            var busControl = _transport.GetBusControl(ConfigureReceiveEndpoint);

            _client = new MessageRequestClient<RequestMessage, ResponseMessage>(busControl, _transport.TargetEndpointAddress, _settings.RequestTimeout);

            try
            {
                Console.WriteLine("Running Request Response Benchmark");

                TaskUtil.Await(() => RunBenchmark(), cancellationToken);

                Console.WriteLine("Message Count: {0}", _settings.MessageCount);
                Console.WriteLine("Clients: {0}", _settings.Clients);
                Console.WriteLine("Durable: {0}", _settings.Durable);
                Console.WriteLine("Prefetch Count: {0}", _settings.PrefetchCount);
                Console.WriteLine("Concurrency Limit: {0}", _settings.ConcurrencyLimit);

                Console.WriteLine("Total consume duration: {0:g}", _consumeDuration);
                Console.WriteLine("Consume message rate: {0:F2} (msg/s)",
                    _settings.MessageCount * 1000 / _consumeDuration.TotalMilliseconds);
                Console.WriteLine("Total request duration: {0:g}", _requestDuration);
                Console.WriteLine("Request rate: {0:F2} (msg/s)",
                    _settings.MessageCount * 1000 / _requestDuration.TotalMilliseconds);
                Console.WriteLine("Concurrent Consumer Count: {0}", RequestConsumer.MaxConsumerCount);

                MessageMetric[] messageMetrics = _capture.GetMessageMetrics();

                Console.WriteLine("Avg Request Time: {0:F0}ms",
                    messageMetrics.Average(x => x.RequestLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("Min Request Time: {0:F0}ms",
                    messageMetrics.Min(x => x.RequestLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("Max Request Time: {0:F0}ms",
                    messageMetrics.Max(x => x.RequestLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("Med Request Time: {0:F0}ms",
                    messageMetrics.Median(x => x.RequestLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("95t Request Time: {0:F0}ms",
                    messageMetrics.Percentile(x => x.RequestLatency) * 1000 / Stopwatch.Frequency);

                Console.WriteLine("Avg Consume Time: {0:F0}ms",
                    messageMetrics.Average(x => x.ConsumeLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("Min Consume Time: {0:F0}ms",
                    messageMetrics.Min(x => x.ConsumeLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("Max Consume Time: {0:F0}ms",
                    messageMetrics.Max(x => x.ConsumeLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("Med Consume Time: {0:F0}ms",
                    messageMetrics.Median(x => x.ConsumeLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("95t Consume Time: {0:F0}ms",
                    messageMetrics.Percentile(x => x.ConsumeLatency) * 1000 / Stopwatch.Frequency);

                Console.WriteLine();

                Console.WriteLine("Request duration distribution");

                DrawResponseTimeGraph(messageMetrics, x => x.RequestLatency);
            }
            finally
            {
                busControl.Stop();
            }
        }
Exemple #38
0
 public CouchApiAttachment(IRequestClient requestClient)
     : base(requestClient)
 {
 }
Exemple #39
0
		public AsyncCards(IRequestClient restClient)
		{
			_restClient = restClient;
		}
 public CouchApiDesignDocCommandRewrite(IRequestClient requestClient)
     : base(requestClient)
 {
 }
Exemple #41
0
 public CouchApiConfig(IRequestClient requestClient)
     : base(requestClient)
 {
 }
Exemple #42
0
		public AsyncLists(IRequestClient restClient)
		{
			_restClient = restClient;
		}
Exemple #43
0
        public void Setup()
        {
            _requestClient = new MessageRequestClient<PingMessage, PongMessage>(Bus, InputQueueAddress, TestTimeout);

            _response = _requestClient.Request(new PingMessage());
        }
 public CouchApiDesignDocCommandList(IRequestClient requestClient)
     : base(requestClient)
 {
 }
 public CouchApiConfigSectionKey(IRequestClient requestClient)
     : base(requestClient)
 {
 }
 public void Setup()
 {
     _requestClient = CreateRequestClient<PerformanceRequest, PerformanceResult>();
 }
 public CouchApiRootCommand(IRequestClient requestClient)
     : base(requestClient)
 {
 }
Exemple #48
0
        public async Task Setup()
        {
            _requestClient = await Host.CreateRequestClient<PingMessage, PongMessage>(Bus, InputQueueAddress, TestTimeout);

            _response = _requestClient.Request(new PingMessage());
        }
Exemple #49
0
 public CouchApiDesignDoc(IRequestClient requestClient)
     : base(requestClient)
 {
 }
Exemple #50
0
	    public AsyncMembers(IRequestClient restClient)
		{
		    _restClient = restClient;
		}
Exemple #51
0
 public CouchApiDb(IRequestClient requestClient)
     : base(requestClient)
 {
 }
Exemple #52
0
 public AsyncActions(IRequestClient restClient)
 {
     _restClient = restClient;
 }
Exemple #53
0
		public AsyncNotifications(IRequestClient restClient)
		{
			_restClient = restClient;
		}
Exemple #54
0
		public AsyncTokens(IRequestClient restClient)
		{
			_restClient = restClient;
		}
 public OrderController(IRequestClient<CheckOrderStatus, OrderStatusResult> client)
 {
     _client = client;
 }
Exemple #56
0
 public CouchApiRoot(IRequestClient requestClient)
 {
     RequestClient = requestClient;
     PathElement = "/";
 }
        public void Setup()
        {
            _requestClient = CreateRequestClient<PingMessage, PongMessage>();

            _response = _requestClient.Request(new PingMessage());
        }
Exemple #58
0
		public AsyncChecklists(IRequestClient restClient)
		{
			_restClient = restClient;
		}
 public CouchApiDesignDocAttachment(IRequestClient requestClient)
     : base(requestClient)
 {
 }
Exemple #60
0
		public AsyncOrganizations(IRequestClient restClient)
		{
			_restClient = restClient;
		}