Пример #1
0
        public virtual async Task Start(CancellationToken cancellationToken = default)
        {
            _received = new BusTestReceiveObserver(TestInactivityTimeout);
            _received.ConnectInactivityObserver(InactivityObserver);

            _consumed = new BusTestConsumeObserver(TestTimeout, InactivityToken);
            _consumed.ConnectInactivityObserver(InactivityObserver);

            _published = new BusTestPublishObserver(TestTimeout, TestInactivityTimeout, InactivityToken);
            _published.ConnectInactivityObserver(InactivityObserver);

            _sent = new BusTestSendObserver(TestTimeout, TestInactivityTimeout, InactivityToken);
            _sent.ConnectInactivityObserver(InactivityObserver);

            PreCreateBus?.Invoke(this);

            BusControl = CreateBus();

            ConnectObservers(BusControl);

            _busHandle = await BusControl.StartAsync(cancellationToken).ConfigureAwait(false);

            BusSendEndpoint = await GetSendEndpoint(BusControl.Address).ConfigureAwait(false);

            InputQueueSendEndpoint = await GetSendEndpoint(InputQueueAddress).ConfigureAwait(false);

            InputQueueSendEndpoint.ConnectSendObserver(_sent);

            BusControl.ConnectConsumeObserver(_consumed);
            BusControl.ConnectPublishObserver(_published);
            BusControl.ConnectReceiveObserver(_received);
            BusControl.ConnectSendObserver(_sent);
        }
Пример #2
0
 protected async Task <TResponse> SendRequest <TRequest, TResponse>(TRequest request,
                                                                    CancellationToken cancellationToken = default(CancellationToken))
     where TRequest : class
     where TResponse : class
 {
     return(await BusControl.SendRequest <TRequest, TResponse>(request, cancellationToken));
 }
Пример #3
0
        public static void Configure()
        {
            CheckinResults = new List <CheckResultadosModel>();

            BusControl = Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                var host = cfg.Host(new Uri(_configuration["BusMensage:host"]), h =>
                {
                    h.Username(_configuration["BusMensage:user"]);
                    h.Password(_configuration["BusMensage:password"]);
                });

                #region ...

                cfg.ReceiveEndpoint(host, e => { /*e.Consumer<CheckEnventoSuscriptores>();*/ });

                //cfg.ConfigureSend(x => x.UseSendExecute(context =>
                //{
                //    context.Headers.Set("prueba", "prueba_q");
                //}));

                #endregion
            });

            BusControl.Start();
        }
            public async Task StartAsync(CancellationToken cancellationToken = new CancellationToken())
            {
                var startTask = Task.CompletedTask;

                lock (this)
                {
                    if (!IsBusControlCreated)
                    {
                        BusControl = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
                        {
                            var host = cfg.Host(HostConfiguration.ServiceUri, HostConfiguration.ConfigureHost);
                            foreach (var queue in QueueConfigurations)
                            {
                                cfg.ReceiveEndpoint(
                                    host,
                                    queue.Key, c =>
                                {
                                    foreach (var action in queue.Value)
                                    {
                                        action(c, host);
                                    }
                                });
                            }
                        });
                        IsBusControlCreated = true;
                        startTask           = BusControl.StartAsync(cancellationToken);
                    }
                }

                await startTask;
            }
        public async Task Should_clean_up_properly()
        {
            async Task ConnectAndRequest()
            {
                var handle = Bus.ConnectResponseEndpoint();

                await handle.Ready;

                await using var clientFactory = await handle.CreateClientFactory();

                using RequestHandle <PingMessage> requestHandle = clientFactory.CreateRequest(new PingMessage());

                await requestHandle.GetResponse <PongMessage>();

                await handle.StopAsync(TestCancellationToken);
            }

            for (var i = 0; i < 10; i++)
            {
                await ConnectAndRequest();
            }

            var health = BusControl.CheckHealth();

            foreach (KeyValuePair <string, EndpointHealthResult> healthEndpoint in health.Endpoints)
            {
                TestContext.WriteLine("Endpoint: {0}, Status: {1}", healthEndpoint.Key, healthEndpoint.Value.Description);
            }

            Assert.That(health.Status, Is.EqualTo(BusHealthStatus.Healthy));
        }
 public void Dispose()
 {
     ScopedBusControl?.StopAsync();
     BusControl?.StopAsync();
     ServiceScope?.Dispose();
     Logger.LogInformation($"{Id} Bus stopped, scope disposed");
 }
        public void Validate(TModel model)
        {
            var query  = new GetUserByEmail(model.Email);
            var result = BusControl.SendRequest <IGetUserByEmail, IGetUserResult>(query).Result;

            if (result.User != null)
            {
                throw new Exception(ExceptionInfo.EmailAlreadyExists.Message);
            }
        }
Пример #8
0
        public static void Main(string[] args)
        {
            try
            {
                var options = new ImagingOptions();

                Container = IocConfig.RegisterDependencies(options);
                LogConfig.RegisterLogs();

                if (CommandLine.Parser.Default.ParseArguments(args, options))
                {
                    Log.Error("Invalid parameters");

                    // Values are available here
                    if (options.Verbose)
                    {
                        Log.Information($"Queue Name: {options.QueueName}");
                        Log.Information($"Usage: {Environment.NewLine}{options.GetUsage()}");
                    }

                    return;
                }

                Log.Information($"Starting Imaging Worker with options {args}");

                Log.Information("Creating bus");
                BusControl = Container.Resolve <IBusControl>();

                Log.Information("Starting bus");
                BusHandle = BusControl.Start();

                Console.WriteLine("Press any key to exit");
                Console.ReadLine();
            }
            catch (Exception ex1)
            {
                Log.Fatal(ex1, "Imaging Worker Error");
                Console.ReadLine();
            }
            finally
            {
                if (BusHandle != null)
                {
                    try
                    {
                        Log.Information("Stopping bus");
                        BusHandle.Stop();
                    }
                    catch (Exception ex2)
                    {
                        Log.Warning(ex2, "Error while stopping bus");
                    }
                }
            }
        }
 public async Task StopAsync(CancellationToken cancellationToken = new CancellationToken())
 {
     lock (this)
     {
         if (!IsBusControlCreated)
         {
             return;
         }
     }
     await BusControl.StopAsync(cancellationToken);
 }
Пример #10
0
        public void SellUsdTest()
        {
            BusControl.Publish <SellCurrency>(new
            {
                Id      = Guid.NewGuid(),
                Created = DateTime.Now,
                Amount  = 5,
                Bid     = 1
            }).GetAwaiter().GetResult();

            Assert.True(true);
        }
Пример #11
0
        public async Task Send <T>(T command, string queueName = "") where T : class
        {
            BusControl = BusControl ?? BuildBus();
            if (queueName == string.Empty)
            {
                queueName = command.GetType().Assembly.GetName().Name + "_CoolBus";
            }

            var sendToUri = new Uri($"rabbitmq://{RabbitConfig.HostName}:{RabbitConfig.Port}/{queueName}");
            var endPoint  = await BusControl.GetSendEndpoint(sendToUri);

            await endPoint.Send(command);
        }
        /// <summary>
        /// Method to run the test case
        /// </summary>
        /// <param name="busControl">
        /// The bus for the test case to use
        /// </param>
        public override async Task Run(BusControl busControl)
        {
            var hostUri = busControl.Instance.Address;

            var address        = new Uri($"{hostUri.Scheme}://{hostUri.Host}/{QueueName}");
            var requestTimeout = TimeSpan.FromSeconds(30);

            var requestClient =
                new MessageRequestClient <IRequestMessage, IResponseMessage>(busControl.Instance, address, requestTimeout);

            await SendMessages(message =>
                               requestClient.Request(message).ConfigureAwait(false)
                               );
        }
Пример #13
0
        public async Task Should_be_degraded_after_too_many_exceptions()
        {
            Assert.That(await BusControl.WaitForHealthStatus(BusHealthStatus.Healthy, TimeSpan.FromSeconds(10)), Is.EqualTo(BusHealthStatus.Healthy));

            await Task.WhenAll(Enumerable.Range(0, 20).Select(x => Bus.Publish(new BadMessage())));

            Assert.That(await BusControl.WaitForHealthStatus(BusHealthStatus.Degraded, TimeSpan.FromSeconds(15)), Is.EqualTo(BusHealthStatus.Degraded));

            Assert.That(await BusControl.WaitForHealthStatus(BusHealthStatus.Healthy, TimeSpan.FromSeconds(10)), Is.EqualTo(BusHealthStatus.Healthy));

            await Task.WhenAll(Enumerable.Range(0, 20).Select(x => Bus.Publish(new GoodMessage())));

            Assert.That(await InMemoryTestHarness.Consumed.SelectAsync <BadMessage>().Take(20).Count(), Is.EqualTo(20));

            Assert.That(await InMemoryTestHarness.Consumed.SelectAsync <GoodMessage>().Take(20).Count(), Is.EqualTo(20));
        }
Пример #14
0
 /**
  * @brief Links all the component so they
  *        can be used in micro instructions.
  */
 public void LinkCPUcomponents(
     ProgramCounter PC, MemoryAddressRegister MAR,
     MemoryDataRegister MDR, InstructionRegister IR,
     GeneralPurposeRegisterA GPA, GeneralPurposeRegisterB GPB,
     ProcessStatusRegister PSR,
     MemoryListControl memory, ArithmeticLogicUnit ALU,
     Clock clock, BusControl busSystem)
 {
     this.PC        = PC;
     this.MAR       = MAR;
     this.MDR       = MDR;
     this.IR        = IR;
     this.GPA       = GPA;
     this.GPB       = GPB;
     this.PSR       = PSR;
     this.memory    = memory;
     this.ALU       = ALU;
     this.clock     = clock;
     this.busSystem = busSystem;
 }
Пример #15
0
        public async Task Token(TokenUserModel model)
        {
            if (!ModelState.IsValid)
            {
                Response.StatusCode = 400;
                await Response.WriteAsync("username or password cannot be empty");

                return;
            }

            var email    = model.UserName; //Request.Form["username"];
            var password = model.Password; //Request.Form["password"];

            var query  = new GetUserByEmail(email);
            var result = BusControl.SendRequest <IGetUserByEmail, IGetUserResult>(query).Result;

            var identity = AuthOptions.GetIdentity(email, password, result.User.PasswordHash, result.User.RoleName);

            if (identity == null)
            {
                Response.StatusCode = 400;
                await Response.WriteAsync("Invalid username or password.");

                return;
                //return BadRequest("Invalid username or password.");
            }
            var encodedJwt = AuthOptions.Token(identity);

            var response = new
            {
                accesstoken = encodedJwt,
                username    = identity.Name
            };

            // сериализация ответа
            Response.ContentType = "application/json";
            await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));
        }
Пример #16
0
        public async Task <IActionResult> Register(RegisterUserModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                if (model.CommandId == Guid.Empty)
                {
                    model.CommandId = NewId.NextGuid();
                }

                var command = GetCommand <RegisterUserCommand, RegisterUserModel>(model);
                var result  = await BusControl.SendCommandWithRespond <IRegisterUser, IGetUserResult>(command);

                var identity = AuthOptions.GetIdentity(command.Email, model.NewPassword, result.User.PasswordHash, result.User.RoleName);
                if (identity == null)
                {
                    return(BadRequest("Invalid username or password."));
                }
                var token = AuthOptions.Token(identity);

                return(Accepted(new AuthPostResult <RegisterUserCommand>()
                {
                    CommandId = result.User.Id,
                    Timestamp = command.Timestamp,
                    Token = token,
                }));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
        //************************************
        // Starts monitor bus
        //Written By Parnian Najafi Borazjani
        //************************************
        private void MonitorBus2_Click(object sender, EventArgs e)
        {
            toolStripStatusLabel2.Text = "Monitor Bus On";
            MonitorBus2.Enabled = false;
            StopMonitor2.Enabled = true;
            string format;
            string[] arguments = new string[5];
            if (Monitor_Hex.Checked == true)
                format = "hex";
            else
                format = "decimal";
            try
            {
                arguments[0] = ReceiveInterfaceBox.SelectedItem.ToString();
                arguments[1] = format;
                arguments[2] = CarFilter;
                arguments[3] = Convert.ToString(numericMSB.Value);
                arguments[4] = TransmitInterfaceBox.SelectedItem.ToString();
                //arguments = {ReceiveInterfaceBox.SelectedItem.ToString();, format, CarFilter, Convert.ToString(numericMSB.Value), TransmitInterfaceBox.SelectedItem.ToString() };

                if (backgroundWorkerRead.IsBusy != true)
                {
                    backgroundWorkerRead.RunWorkerAsync(arguments);
                    MonitorBus2.Enabled = false;
                    StopMonitor2.Enabled = true;
                    ErrorLog.NewLogEntry("CAN", "Monitor Bus On");
                }
                else
                {
                    ErrorLog.NewLogEntry("CAN", "Monitor Bus - Background Worker Busy");
                }
            }
            catch
            {
                MessageBox.Show("No interface is turned on, please turn on the interfaces from \"Advanced Bus Control\"");
                this.Close();
                BusControl form = (BusControl)CommonUtils.GetOpenedForm<BusControl>();
                if (form == null)
                {
                    form = new BusControl();
                    form.Show();
                }
                else
                {
                    form.Select();
                }
            }
        }
Пример #18
0
        public static IGetUserResult GetUser(string email)
        {
            var query = new GetUserByEmail(email);

            return(BusControl.SendRequest <IGetUserByEmail, IGetUserResult>(query).Result);
        }
 public void Start()
 {
     InitializeBusUsingRabbitMq();
     BusControl.Start();
 }
 /// <summary>
 /// Method to run the test case
 /// </summary>
 /// <param name="busControl">
 /// The bus for the test case to use
 /// </param>
 public override async Task Run(BusControl busControl)
 {
     await SendMessages(message =>
                        busControl.Instance.Publish <ICatalogueRequest>(message).ConfigureAwait(false)
                        );
 }
 /// <summary>
 /// Method to run the test benchmark
 /// </summary>
 /// <param name="busControl">
 /// The bus for the test case to use
 /// </param>
 public abstract Task Run(BusControl busControl);
Пример #22
0
 protected async Task Send <TMessage>(TMessage message,
                                      CancellationToken cancellationToken = default(CancellationToken))
     where TMessage : class
 {
     await BusControl.Send(message, cancellationToken);
 }
Пример #23
0
 public async Task Publish <T>(T @event) where T : class
 {
     BusControl = BusControl ?? BuildBus();
     await BusControl.Publish(@event);
 }
Пример #24
0
 public async Task <ISendEndpoint> GetSendEndpoint(Uri address)
 {
     return(await BusControl.GetSendEndpoint(address).ConfigureAwait(false));
 }
Пример #25
0
 public override Task Run(BusControl busControl)
 {
     throw new NotImplementedException();
 }