Exemplo n.º 1
0
    protected void lnkBtnSave_Click(object sender, EventArgs e)
    {
        string busPlate = BusPlate.Text;
        string busName = BusName.Text;
        string seat = Seat.Text;
        string busTypeId = ddlBusType.SelectedValue.ToString();
        string categoryID = ddlCategory.SelectedValue.ToString();

        if (BLLBus.checkBusPlateExist(busPlate) != 0)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "Notify", "alert('!!!Bus Plate existed. Please try again');", true);
        }
        else
        {
            Bus bus = new Bus();
            bus.BusPlate = busPlate;
            bus.BusName = busName;
            bus.Seat = Int32.Parse(seat);
            bus.BusTypeID = Int32.Parse(busTypeId);
            bus.CategoryID = Int32.Parse(categoryID);
            bus.Status = true;
            BLLBus.InsertBus(bus);
            Response.Redirect("BusList.aspx");
        }
    }
Exemplo n.º 2
0
        internal static Bus Build(BusBuilderConfiguration configuration)
        {
            var logger = configuration.Logger;
            logger.Debug("Constructing bus...");

            var container = new PoorMansIoC();

            RegisterPropertiesFromConfigurationObject(container, configuration);
            RegisterPropertiesFromConfigurationObject(container, configuration.LargeMessageStorageConfiguration);
            RegisterPropertiesFromConfigurationObject(container, configuration.Debugging);

            container.Register<Func<NamespaceManager>> (() =>
            {
                var ns = NamespaceManager.CreateFromConnectionString(container.Resolve<ConnectionStringSetting>());
                ns.Settings.OperationTimeout = configuration.DefaultTimeout;
                return ns;
            });
        
            container.Register<Func<MessagingFactory>>(() =>
            {
                var messagingFactory = MessagingFactory.CreateFromConnectionString(container.Resolve<ConnectionStringSetting>());
                messagingFactory.PrefetchCount = container.Resolve<ConcurrentHandlerLimitSetting>();
                return messagingFactory;
            });
   

            if (configuration.Debugging.RemoveAllExistingNamespaceElements)
            {
                var namespaceCleanser = container.Resolve<NamespaceCleanser>();
                namespaceCleanser.RemoveAllExistingNamespaceElements().Wait();
            }

            logger.Debug("Creating message receivers...");

            var messageReceiverManager = new MessageRecevierManager(
                container.Resolve<CommandMessageReceiverFactory>().CreateAll(),
                container.Resolve<MulticastEventMessageReceiverFactory>().CreateAll(),
                container.Resolve<CompetingEventMessageReceiverFactory>().CreateAll());

            logger.Debug("Message receivers are all created.");

            var bus = new Bus(container.Resolve<IZombusLogger>(),
                              container.Resolve<ICommandSender>(),
                              container.Resolve<IEventSender>(),
                              messageReceiverManager,
                              container.Resolve<DeadLetterQueues>(),
                              container.Resolve<IHeartbeat>());

            bus.Starting += delegate
                            {
                                container.Resolve<AzureQueueManager>().WarmUp();
                                container.Resolve<PropertyInjector>().Bus = bus;
                            };

            bus.Disposing += delegate { container.Dispose(); };

            logger.Info("Bus built. Job done!");

            return bus;
        }
        public void StartMessageShouldCreateANewMessageBusReadStream()
        {
            // Arrange
            var bus = new Bus(_mockConfiguration.Object);

            var mockStream = new Mock<IMessageBusReadStream>();
            mockStream.Setup(x => x.HandlerCount).Returns(1);
            _mockConsumerPool.Setup(x => x.AddConsumer(It.IsAny<string>(), It.IsAny<IList<string>>(), It.Is<ConsumerEventHandler>(y => AssignEventHandler(y)), It.IsAny<IConfiguration>()));
            var mockProcessor = new Mock<IStreamProcessor>();
            _mockContainer.Setup(x => x.GetInstance<IStreamProcessor>(It.Is<Dictionary<string, object>>(y => y["container"] == _mockContainer.Object))).Returns(mockProcessor.Object);
            mockProcessor.Setup(x => x.ProcessMessage(It.IsAny<FakeMessage1>(), mockStream.Object));
            _mockConfiguration.Setup(x => x.GetMessageBusReadStream()).Returns(mockStream.Object);
            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            bus.StartConsuming();

            // Act
            _fakeEventHandler(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)), typeof(FakeMessage1).AssemblyQualifiedName, new Dictionary<string, object>
            {
                { "Start", "" },
                { "SequenceId", Encoding.UTF8.GetBytes("TestSequence") },
                { "SourceAddress", Encoding.UTF8.GetBytes("Source") },
                { "RequestMessageId", Encoding.UTF8.GetBytes("MessageId") },
                { "MessageType", Encoding.UTF8.GetBytes("ByteStream")}
            });

            // Assert
            mockProcessor.Verify(x => x.ProcessMessage(It.IsAny<FakeMessage1>(), It.IsAny<IMessageBusReadStream>()), Times.Once);
        }
Exemplo n.º 4
0
        public virtual async Task Given(ITestHarnessBusFactory busFactory)
        {
            Bus = (Bus) busFactory.Create();

            Console.WriteLine();
            Console.WriteLine();
        }
Exemplo n.º 5
0
        public void StartConsumingShouldConsumeAllMessageTypes()
        {
            // Arrange
            var bus = new Bus(_mockConfiguration.Object);
            _mockConsumer.Setup(x => x.ConsumeMessageType(It.IsAny<string>()));

            var handlerReferences = new List<HandlerReference>
            {
                new HandlerReference
                {
                    HandlerType = typeof (FakeHandler1),
                    MessageType = typeof (FakeMessage1)
                },
                new HandlerReference
                {
                    HandlerType = typeof (FakeHandler2),
                    MessageType = typeof (FakeMessage2)
                }
            };

            _mockContainer.Setup(x => x.GetHandlerTypes()).Returns(handlerReferences);

            _mockConsumerPool.Setup(x => x.AddConsumer(It.IsAny<string>(), It.Is<IList<string>>(m => m.Contains(typeof(FakeMessage1).FullName.Replace(".", string.Empty)) && m.Contains(typeof(FakeMessage2).FullName.Replace(".", string.Empty))), It.IsAny<ConsumerEventHandler>(), It.IsAny<IConfiguration>()));

            // Act
            bus.StartConsuming();

            // Assert
            _mockContainer.VerifyAll();
            _mockConsumerPool.Verify(x => x.AddConsumer(It.IsAny<string>(), It.Is<IList<string>>(m => m.Contains(typeof(FakeMessage1).FullName.Replace(".", string.Empty)) && m.Contains(typeof(FakeMessage2).FullName.Replace(".", string.Empty))), It.IsAny<ConsumerEventHandler>(), It.IsAny<IConfiguration>()), Times.Once);
        }
Exemplo n.º 6
0
        public static void Init()
        {
            var bus = new Bus();

            var cashier = new Cashier(bus);
            var barista = new Barista(Guid.NewGuid(), bus);

            var repository = new SagaRepository<OrderFufillment>(bus);
            bus.RouteToSaga(repository, (DrinkOrdered e) => e.OrderId);
            bus.RouteToSaga(repository, (DrinkPrepared e) => e.OrderId);
            bus.RouteToSaga(repository, (PaymentReceived e) => e.OrderId);

            bus.Register<OrderDrink>(c => cashier.Order(c.OrderId, c.Drink));
            bus.RegisterOnThreadPool<Pay>(c => cashier.Pay(c.OrderId, PaymentMethod.CreditCard, c.Amount));
            bus.RegisterOnThreadPool<PrepareDrink>(c => barista.PrepareDrink(c.OrderId, c.Drink));
            bus.Register<NotifyCustomer>(c =>
                                             {
                                                 Console.WriteLine("{0} is ready", c.OrderId);
                                                 ThreadPool.QueueUserWorkItem(_ => bus.Send(new Pay
                                                                                                {
                                                                                                    OrderId =
                                                                                                        c.OrderId,
                                                                                                    Amount = 12m
                                                                                                }));
                                             });

            ServiceLocator.RegisterDispatcher<Command>(bus.Send);

            WindowsCommunicationFoundation.RegisterServiceLayer<Sales>();
        }
Exemplo n.º 7
0
        public static Point Interpolate(Bus bus, List<Point> path, double timeNow)
        {
            int lastTime = bus.lastStop.stopMinuteTime;
            int nextTime = bus.nextStop.stopMinuteTime;
            double fractionComplete = (timeNow - lastTime) / (nextTime - lastTime);
            double distanceRequired = bus.lengthOfLeg * fractionComplete;

            double finalLineFraction = 0;
            bool atThePoint = false;
            int i = bus.lastStopIndex;
            while (!atThePoint)
            {
                double lineLength = Distance(path[i], path[i + 1]);
                if (lineLength > distanceRequired)
                {
                    atThePoint = true;
                    finalLineFraction = distanceRequired / lineLength;
                }
                else
                {
                    distanceRequired -= lineLength;
                    i++;
                }
            }
            int x = (int)(path[i].X + finalLineFraction * (path[i + 1].X - path[i].X));
            int y = (int)(path[i].Y + finalLineFraction * (path[i + 1].Y - path[i].Y));
            return new Point((int)x, (int)y);
        }
        public void CreateStreamShouldCreateAMessageBusWriteStream()
        {
            // Arrange
            var mockConfiguration = new Mock<IConfiguration>();
            var mockProducer = new Mock<IProducer>();
            var mockContainer = new Mock<IBusContainer>();
            var mockRequestConfiguration = new Mock<IRequestConfiguration>();
            var mockStream = new Mock<IMessageBusWriteStream>();

            mockConfiguration.Setup(x => x.GetContainer()).Returns(mockContainer.Object);
            mockConfiguration.Setup(x => x.GetProducer()).Returns(mockProducer.Object);
            mockConfiguration.SetupGet(x => x.TransportSettings).Returns(new TransportSettings ());
            mockConfiguration.Setup(x => x.GetRequestConfiguration(It.IsAny<Guid>())).Returns(mockRequestConfiguration.Object);
            mockConfiguration.Setup(x=> x.GetMessageBusWriteStream(It.IsAny<IProducer>(), "TestEndpoint", It.IsAny<string>(), It.IsAny<IConfiguration>())).Returns(mockStream.Object);
            var task = new Task(() => { });
            mockRequestConfiguration.Setup(x => x.SetHandler(It.IsAny<Action<object>>())).Returns(task);

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            mockProducer.Setup(x => x.Send(It.IsAny<string>(), It.IsAny<Type>(), It.IsAny<byte[]>(), It.IsAny<Dictionary<string, string>>())).Callback(task.Start);

            // Act
            var bus = new Bus(mockConfiguration.Object);

            // Act
            var stream = bus.CreateStream("TestEndpoint", message);

            // Assert
            Assert.NotNull(stream);
            Assert.Equal(mockStream.Object, stream);
        }
Exemplo n.º 9
0
    public static void Main()
    {
        BusG.Init ();
        Application.Init ();

        Window win = new Window ("D-Bus#");
        win.SetDefaultSize (640, 480);
        win.Destroyed += delegate {Application.Quit ();};
        win.ShowAll ();

        bus = Bus.Session;
        sysBus = Bus.System.GetObject<IBus> ("org.freedesktop.DBus", new ObjectPath ("/org/freedesktop/DBus"));

        string bus_name = "org.ndesk.gtest";
        ObjectPath path = new ObjectPath ("/org/ndesk/test");

        if (bus.RequestName (bus_name) == RequestNameReply.PrimaryOwner) {
            //create a new instance of the object to be exported
            demo = new DemoObject ();
            sysBus.NameOwnerChanged += demo.FireChange;
            bus.Register (path, demo);
        } else {
            //import a remote to a local proxy
            demo = bus.GetObject<DemoObject> (bus_name, path);
        }

        //run the main loop
        Application.Run ();
    }
Exemplo n.º 10
0
        public void CanPublish()
        {
            var mockRepository = new MockRepository();
            var config = mockRepository.DynamicMock<IBrokerConfiguration>();
            var connFactory = mockRepository.DynamicMock<IBrokerConnectionFactory>();
            var conn = mockRepository.DynamicMock<IBrokerConnection>();
            var consumer = mockRepository.DynamicMock<IRegisteredConsumer>();
            var message = new TestMessage();

            using (mockRepository.Record())
            {
                SetupResult.For(consumer.MessageType).Return(typeof(TestMessage));
                SetupResult.For(connFactory.CreateConnection()).Return(conn);
                SetupResult.For(config.Exchange).Return("ex");
                SetupResult.For(config.ConnectionFactory).Return(connFactory);
                SetupResult.For(config.RegisteredConsumers).Return(new Dictionary<Type, IList<IRegisteredConsumer>> { { typeof(TestMessage), new List<IRegisteredConsumer> { consumer } } }); ;
                SetupResult.For(conn.IsOpen).Return(true);

                Expect.Call(() => conn.Publish<TestMessage>(null))
                    .IgnoreArguments()
                    .WhenCalled(mi =>
                            {
                                var envelope = mi.Arguments[0];

                                Assert.IsAssignableFrom(typeof(IMessageEnvelope<TestMessage>), envelope);
                                Assert.Same(message, ((IMessageEnvelope<TestMessage>)envelope).Message);
                            });
            }

            using (mockRepository.Playback())
            {
                var bus = new Bus(config);
                bus.Publish(message);
            }
        }
Exemplo n.º 11
0
        public void ClosesOpenConnectionOnDispose()
        {
            var mockRepository = new MockRepository();
            var config = mockRepository.DynamicMock<IBrokerConfiguration>();
            var connFactory = mockRepository.DynamicMock<IBrokerConnectionFactory>();
            var conn = mockRepository.DynamicMock<IBrokerConnection>();
            var consumer = mockRepository.DynamicMock<IRegisteredConsumer>();

            using (mockRepository.Record())
            {
                SetupResult.For(consumer.MessageType).Return(typeof (TestMessage));
                SetupResult.For(connFactory.CreateConnection()).Return(conn);
                SetupResult.For(config.ConnectionFactory).Return(connFactory);
                SetupResult.For(config.RegisteredConsumers).Return(new Dictionary<Type, IList<IRegisteredConsumer>> { { typeof(TestMessage), new List<IRegisteredConsumer> { consumer } } });
                SetupResult.For(conn.IsOpen).Return(true);

                Expect.Call(conn.Close);
            }

            using (mockRepository.Playback())
            {
                var bus = new Bus(config);
                bus.GetLiveConnection();
                bus.Dispose();
            }
        }
Exemplo n.º 12
0
	void Awake() 
    {
        bus = GetComponent<Bus>();
        bus.PropertyChanged += OnPropertyChanged;

        audio = gameObject.AddComponent<AudioSource>();
	}
Exemplo n.º 13
0
    public static void Main()
    {
        BusG.Init ();
        Application.Init ();

        Button btn = new Button ("Click me");
        btn.Clicked += OnClick;

        VBox vb = new VBox (false, 2);
        vb.PackStart (btn, false, true, 0);

        Window win = new Window ("D-Bus#");
        win.SetDefaultSize (640, 480);
        win.Add (vb);
        win.Destroyed += delegate {Application.Quit ();};
        win.ShowAll ();

        bus = Bus.Session;

        string bus_name = "org.ndesk.gtest";
        ObjectPath path = new ObjectPath ("/org/ndesk/test");

        if (bus.RequestName (bus_name) == RequestNameReply.PrimaryOwner) {
            //create a new instance of the object to be exported
            demo = new DemoObject ();
            bus.Register (path, demo);
        } else {
            //import a remote to a local proxy
            demo = bus.GetObject<DemoObject> (bus_name, path);
        }

        //run the main loop
        Application.Run ();
    }
Exemplo n.º 14
0
        public Coordinator(Bus.Attachment.IFactory attachmentFactory, Bus.Object.IFactory objectFactory)
        {
            _attachmentFactory = attachmentFactory;
            _objectFactory = objectFactory;

            _objects = new Dictionary<string, Object.Instance>();
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            IBusLog log = new BusLog();

            try
            {
                using (IBus bus = new Bus(@".\private$\testreq", @".\private$\", @".\private$\testack", null, null, log))
                {
                    bus.BusLoggingLevel = BusLoggingLevel.Diagnostic;

                    bus.RegisterHandler<ARequest, AResponse, AHandler>();
                    bus.RegisterHandler<BRequest, BResponse, BHandler>();
                    bus.RegisterHandler<CRequest, CResponse, CHandler>();
                    bus.RegisterHandler<DRequest, DResponse, DHandler>();

                    bus.StartListening();

                    log.Info("Server ready. Press Enter to quit.");
                    Console.ReadLine();

                    bus.StopListening();

                    Console.WriteLine("Total sent: " + bus.TotalSent);
                    Console.WriteLine("Total received: " + bus.TotalReceived);

                    Thread.Sleep(5000);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                Thread.Sleep(5000);
            }
        }
Exemplo n.º 16
0
        public void Test()
        {
            var bus = new Bus<Int32>();
            bus.SendLocal(34);

/*            bus.Where(i => i > 100).Subscribe(i =>
            {
                Console.WriteLine("New Message Arrived {0}", i);
            });

            var dis = bus.Subscribe(i =>
            {
                Console.WriteLine("||| New Message Arrived {0}", i);
            });*/

            bus.SendLocal(346);
            bus.Run();

            bus.SendLocal(777);

//            dis.Dispose();

            bus.SendLocal(888);



            
        }
Exemplo n.º 17
0
        public static IBus Connect(DepotSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            settings.Validate();

            var connectionString = settings.ConnectionString;
            var connectionFactory = settings.ConnectionFactoryBuilder();
            var consumerFactory = settings.ConsumerFactoryBuilder();

            var modelFactory = connectionFactory.Create(new Uri(connectionString));
            var messageSerializers = settings.MessageSerializers;

            var bus = new Bus(
                modelFactory,
                consumerFactory,
                new RequesterFactory(),
                new PublisherFactory(messageSerializers),
                new SubscriptionFactory(modelFactory, messageSerializers));

            foreach (var concern in settings.StartupConcerns)
            {
                concern.Run(bus);
            }

            return bus;
        }
        private static void RegisterHandlersInAssembly(IEnumerable<Assembly> assemblies, Type messageType, Bus.Bus bus, Type[] ctorArgTypes, object[] ctorArgs)
        {
            //among classes in handlers assemblies select any which handle specified message type
            var handlerTypesWithMessages = assemblies
                                        .SelectMany(a => a.GetTypes())
                                        .Where(t => !t.IsInterface && t.GetInterfaces()
                                            .Any(i => i.IsGenericType
                                                && i.GetGenericTypeDefinition() == typeof(IHandle<>)
                                                && messageType.IsAssignableFrom(i.GetGenericArguments().First())))
                                        .Select(t => new
                                        {
                                            Type = t,
                                            MessageTypes = t.GetInterfaces().Select(i => i.GetGenericArguments().First())
                                        });

            foreach (var handler in handlerTypesWithMessages)
            {
                var ctor = handler.Type.GetConstructor(ctorArgTypes);
                var handlerInstance = ctor.Invoke(ctorArgs);

                foreach (Type msgType in handler.MessageTypes)
                {
                    MethodInfo handleMethod = handler.Type
                                                .GetMethods()
                                                .Where(m => m.Name.Equals("Handle", StringComparison.OrdinalIgnoreCase))
                                                .First(m => msgType.IsAssignableFrom(m.GetParameters().First().ParameterType));

                    Type actionType = typeof(Action<>).MakeGenericType(msgType);
                    Delegate handlerDelegate = Delegate.CreateDelegate(actionType, handlerInstance, handleMethod);

                    MethodInfo genericRegister = bus.GetType().GetMethod("RegisterHandler").MakeGenericMethod(new[] { msgType });
                    genericRegister.Invoke(bus, new[] { handlerDelegate });
                }
            }
        }
Exemplo n.º 19
0
    public static void Main()
    {
        BusG.Init ();
        Application.Init ();

        btn = new Button ("Click me");
        btn.Clicked += OnClick;

        VBox vb = new VBox (false, 2);
        vb.PackStart (btn, false, true, 0);

        Window win = new Window ("D-Bus#");
        win.SetDefaultSize (640, 480);
        win.Add (vb);
        win.Destroyed += delegate {Application.Quit ();};
        win.ShowAll ();

        bus = Bus.Session;

        string bus_name = "org.ndesk.gtest";
        ObjectPath path = new ObjectPath ("/org/ndesk/btn");

        if (bus.RequestName (bus_name) == RequestNameReply.PrimaryOwner) {
            bus.Register (path, btn);
            rbtn = btn;
        } else {
            rbtn = bus.GetObject<Button> (bus_name, path);
        }

        //run the main loop
        Application.Run ();
    }
Exemplo n.º 20
0
        public void BusCanRouteMessages()
        {
            // Arrange
            var sut = new Bus();

            // Assert
            Assert.True(sut.TotalMessagesDelivered > 0);
        }
Exemplo n.º 21
0
        public void Painter_should_paint_bus_with_given_color()
        {
            var painter = new Painter();
            var bus = new Bus("REG");
            painter.Paint(bus, Color.HotPink);

            Assert.AreEqual(Color.HotPink, bus.Color);
        }
Exemplo n.º 22
0
        public void When_sending_a_command_and_there_are_no_command_handlers_should_throw_exception()
        {
            var serviceContainer = new ServiceContainer();
            var bus = new Bus(serviceContainer.GetAllInstances);
            var command = new Command();

            Assert.Throws<NotSupportedException>(() => bus.SendAsync(command).Wait());
        }
Exemplo n.º 23
0
        protected virtual async Task Given(IConfigurationScenario<BusBuilderConfiguration> scenario)
        {
            Instance = scenario.CreateInstance();
            Reconfigure();

            Bus = Instance.Configuration.Build();
            MethodCallCounter = MethodCallCounter.CreateInstance(Bus.InstanceId);
            await Bus.Start();
        }
Exemplo n.º 24
0
 protected void Page_Load(object sender, EventArgs e)
 {
     busPlate = Request.QueryString["BusPlate"].ToString();
     bus = BLLBus.getBusByID(busPlate)[0];
     if (!IsPostBack)
     {
         FillData();
     }
 }
Exemplo n.º 25
0
 public void OnBusEnter(Bus bus)
 {
     if(State == EState.WAITING)
     {
         State = EState.BOARDING;
         targetBus = bus;
         bus.Queue(this);
     }
 }
 public ExpenseReportController(IExpenseReportBuilder expenseReportBuilder, IUserSession session,
     IWorkflowFacilitator workflowFacilitator, Bus bus, ICalendar calendar)
 {
     _expenseReportBuilder = expenseReportBuilder;
     _session = session;
     _workflowFacilitator = workflowFacilitator;
     _bus = bus;
     _calendar = calendar;
 }
Exemplo n.º 27
0
    void Awake()
    {
        vehicle = GetComponent<Vehicle>();
        bus = GetComponent<Bus>();

        vehicle.PropertyChanged += OnPropertyChanged;
        bus.PropertyChanged += OnPropertyChanged;

        doorsUI.onClick.AddListener(() => bus.ToggleDoors());
    }
Exemplo n.º 28
0
		public void Status_Initialised()
		{
			var _busConfigurationBuilder = new BusConfigurationBuilder();
			_busConfigurationBuilder.ConnectionUris.Add(TestingConfiguration.LocalConnectionUri);
			var _busConfirguration = _busConfigurationBuilder.Build();

			var _SUT = new Bus(_busConfirguration);

			Assert.AreEqual(BusStatus.Initialised, _SUT.Status);
		}
Exemplo n.º 29
0
        public static void Main(string[] args)
        {
            Task.Run(() =>
            {
                var bus = new Bus();
                var srv = new BusServer("uuid:" + Guid.NewGuid(), "RNet Bus", "Russound", "CAM6.6", bus);
                srv.Start();
            }).Wait();

            Console.ReadLine();
        }
Exemplo n.º 30
0
        public Task OnStart()
        {
            // Make sure the bus is started
            _bus = _container.Resolve<Bus>();
            Task startBus = _bus.Start();

            // Execute the scheduler that we can cancel on stop
            _schedulerExecution = _container.Resolve<SampleDataJobScheduler>().Run(_cancelTokenSource.Token);

            return startBus;
        }
Exemplo n.º 31
0
                public void Handle(MessageInitiatingSaga message)
                {
                    Context.SagaId = Data.Id;

                    Bus.SendLocal(new MessageSentBySaga());
                }
Exemplo n.º 32
0
        public EditFailedMessages()
        {
            Get["/edit/config"] = _ => Negotiate.WithModel(GetEditConfiguration());

            Post["/edit/{failedmessageid}", true] = async(parameters, token) =>
            {
                if (!Settings.AllowMessageEditing)
                {
                    logging.Info("Message edit-retry has not been enabled.");
                    return(HttpStatusCode.NotFound);
                }

                string failedMessageId = parameters.FailedMessageId;

                if (string.IsNullOrEmpty(failedMessageId))
                {
                    return(HttpStatusCode.BadRequest);
                }

                var edit = this.Bind <EditMessageModel>();

                FailedMessage failedMessage;

                using (var session = Store.OpenAsyncSession())
                {
                    failedMessage = await session.LoadAsync <FailedMessage>(FailedMessage.MakeDocumentId(failedMessageId)).ConfigureAwait(false);
                }

                if (failedMessage == null)
                {
                    logging.WarnFormat("The original failed message could not be loaded for id={0}", failedMessageId);
                    return(HttpStatusCode.BadRequest);
                }

                //WARN

                /*
                 * failedMessage.ProcessingAttempts.Last() return the lat retry attempt.
                 * In theory between teh time someone edits a failed message and retry it someone else
                 * could have retried the same message without editing. If this is the case "Last()" is
                 * not anymore the same message.
                 * Instead of using Last() it's probably better to select the processing attempt by looking for
                 * one with the same MessageID
                 */

                if (LockedHeaderModificationValidator.Check(GetEditConfiguration().LockedHeaders, edit.MessageHeaders.ToDictionary(x => x.Key, x => x.Value), failedMessage.ProcessingAttempts.Last().Headers))
                {
                    logging.WarnFormat("Locked headers have been modified on the edit-retry for MessageID {0}.", failedMessageId);
                    return(HttpStatusCode.BadRequest);
                }

                if (string.IsNullOrWhiteSpace(edit.MessageBody) || edit.MessageHeaders == null)
                {
                    logging.WarnFormat("There is no message body on the edit-retry for MessageID {0}.", failedMessageId);
                    return(HttpStatusCode.BadRequest);
                }

                // Encode the body in base64 so that the new body doesn't have to be escaped
                var base64String = Convert.ToBase64String(Encoding.UTF8.GetBytes(edit.MessageBody));
                await Bus.SendLocal(new EditAndSend
                {
                    FailedMessageId = failedMessageId,
                    NewBody         = base64String,
                    NewHeaders      = edit.MessageHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
                }).ConfigureAwait(false);

                return(HttpStatusCode.Accepted);
            };
        }
Exemplo n.º 33
0
 public DemoValue1Characteristic(Bus bus, int index, Service service) : base(bus, index, UUID, new[] { "read" }, service)
 {
 }
Exemplo n.º 34
0
 public FormDetailBus(Bus bus)
 {
     InitializeComponent();
     DteByHour.Value = DateTime.Now;
     this.bus        = bus;
 }
Exemplo n.º 35
0
 protected override async Task When()
 {
     _response = await Bus.Request(new SomeRequest(), _timeout);
 }
Exemplo n.º 36
0
        public void Handle(ReplicationMessage.DataChunkBulk message)
        {
            Interlocked.Decrement(ref FlushMessagesInQueue);
            try
            {
                if (_subscriptionId != message.SubscriptionId)
                {
                    return;
                }
                if (_activeChunk != null)
                {
                    ReplicationFail("Data chunk bulk received, but we have active chunk for receiving raw chunk bulks.");
                }

                var chunk = Writer.CurrentChunk;
                if (chunk.ChunkHeader.ChunkStartNumber != message.ChunkStartNumber || chunk.ChunkHeader.ChunkEndNumber != message.ChunkEndNumber)
                {
                    Log.Error("Received DataChunkBulk for TFChunk {0}-{1}, but active chunk is {2}-{3}.",
                              message.ChunkStartNumber, message.ChunkEndNumber, chunk.ChunkHeader.ChunkStartNumber, chunk.ChunkHeader.ChunkEndNumber);
                    return;
                }

                if (_subscriptionPos != message.SubscriptionPosition)
                {
                    Log.Error("Received DataChunkBulk at SubscriptionPosition {0} (0x{0:X}) while current SubscriptionPosition is {1} (0x{1:X}).",
                              message.SubscriptionPosition, _subscriptionPos);
                    return;
                }

                _framer.UnFrameData(new ArraySegment <byte>(message.DataBytes));
                _subscriptionPos += message.DataBytes.Length;

                if (message.CompleteChunk)
                {
                    Log.Trace("Completing data chunk {0}-{1}...", message.ChunkStartNumber, message.ChunkEndNumber);
                    Writer.CompleteChunk();

                    if (_framer.HasData)
                    {
                        ReplicationFail("There is some data left in framer when completing chunk.");
                    }

                    _subscriptionPos = chunk.ChunkHeader.ChunkEndPosition;
                    _framer.Reset();
                }
            }
            catch (Exception exc)
            {
                Log.ErrorException(exc, "Exception in writer.");
                throw;
            }
            finally
            {
                Flush();
            }

            if (message.CompleteChunk || _subscriptionPos - _ackedSubscriptionPos >= MasterReplicationService.ReplicaAckWindow)
            {
                _ackedSubscriptionPos = _subscriptionPos;
                Bus.Publish(new ReplicationMessage.AckLogPosition(_subscriptionId, _ackedSubscriptionPos));
            }
        }
Exemplo n.º 37
0
 public void AddToBuses(Bus bus)
 {
     base.AddObject("Buses", bus);
 }
Exemplo n.º 38
0
 private void HoaDon_Load(object sender, EventArgs e)
 {
     dgvHoadon.DataSource    = Bus.GetListHoadon();
     cbxMathuthu.DataSource  = Bus.GetListThuthu();
     cbxMathuthu.ValueMember = "matt";
 }
Exemplo n.º 39
0
 public void Hienthi(string hoadon)
 {
     dgvHoadon.DataSource = Bus.SearchHoadon(hoadon);
 }
Exemplo n.º 40
0
 public IBus StartSQLEndpoint(bool useOutbox)
 {
     return(Bus.Create(EndpointConfig.CreateSQLConfiguration(useOutbox)).Start());
 }
Exemplo n.º 41
0
 public IBus StartAzureEndpoint(string azureSBConnection, bool useOutbox, bool disableTx)
 {
     return(Bus.Create(EndpointConfig.CreateAzureBusConfiguration(azureSBConnection, useOutbox, disableTx)).Start());
 }
Exemplo n.º 42
0
        public async Task <IHttpActionResult> Put(AddSliderToDiscountCommand command)
        {
            var response = await Bus.Send <AddSliderToDiscountCommand, AddSliderToDiscountCommandResponse>(command);

            return(Ok(response));
        }
Exemplo n.º 43
0
        public SingleVNode(TFChunkDb db, SingleVNodeSettings vNodeSettings, SingleVNodeAppSettings appSettings, bool dbVerifyHashes)
        {
            Ensure.NotNull(db, "db");
            Ensure.NotNull(vNodeSettings, "vNodeSettings");

            db.OpenVerifyAndClean(dbVerifyHashes);

            _tcpEndPoint  = vNodeSettings.ExternalTcpEndPoint;
            _httpEndPoint = vNodeSettings.ExternalHttpEndPoint;

            _outputBus  = new InMemoryBus("OutputBus");
            _controller = new SingleVNodeController(Bus, _httpEndPoint);
            _mainQueue  = new QueuedHandler(_controller, "MainQueue");
            _controller.SetMainQueue(MainQueue);

            //MONITORING
            var monitoringInnerBus   = new InMemoryBus("MonitoringInnerBus", watchSlowMsg: false);
            var monitoringRequestBus = new InMemoryBus("MonitoringRequestBus", watchSlowMsg: false);
            var monitoringQueue      = new QueuedHandler(monitoringInnerBus, "MonitoringQueue", watchSlowMsg: true, slowMsgThresholdMs: 100);
            var monitoring           = new MonitoringService(monitoringQueue, monitoringRequestBus, db.Config.WriterCheckpoint, db.Config.Path, appSettings.StatsPeriod);

            Bus.Subscribe(monitoringQueue.WidenFrom <SystemMessage.SystemInit, Message>());
            Bus.Subscribe(monitoringQueue.WidenFrom <SystemMessage.BecomeShuttingDown, Message>());
            monitoringInnerBus.Subscribe <SystemMessage.SystemInit>(monitoring);
            monitoringInnerBus.Subscribe <SystemMessage.BecomeShuttingDown>(monitoring);
            monitoringInnerBus.Subscribe <MonitoringMessage.GetFreshStats>(monitoring);

            //STORAGE SUBSYSTEM
            var indexPath  = Path.Combine(db.Config.Path, "index");
            var tableIndex = new TableIndex(indexPath,
                                            () => new HashListMemTable(maxSize: 2000000),
                                            maxSizeForMemory: 1000000,
                                            maxTablesPerLevel: 2);

            var readIndex = new ReadIndex(_mainQueue,
                                          TFConsts.ReadIndexReaderCount,
                                          () => new TFChunkSequentialReader(db, db.Config.WriterCheckpoint, 0),
                                          () => new TFChunkReader(db, db.Config.WriterCheckpoint),
                                          tableIndex,
                                          new XXHashUnsafe(),
                                          new LRUCache <string, StreamCacheInfo>(TFConsts.MetadataCacheCapacity));
            var writer        = new TFChunkWriter(db);
            var storageWriter = new StorageWriter(_mainQueue, _outputBus, writer, readIndex);
            var storageReader = new StorageReader(_mainQueue, _outputBus, readIndex, TFConsts.StorageReaderHandlerCount, db.Config.WriterCheckpoint);

            monitoringRequestBus.Subscribe <MonitoringMessage.InternalStatsRequest>(storageReader);

            var chaser        = new TFChunkChaser(db, db.Config.WriterCheckpoint, db.Config.ChaserCheckpoint);
            var storageChaser = new StorageChaser(_mainQueue, chaser, readIndex);

            _outputBus.Subscribe <SystemMessage.SystemInit>(storageChaser);
            _outputBus.Subscribe <SystemMessage.SystemStart>(storageChaser);
            _outputBus.Subscribe <SystemMessage.BecomeShuttingDown>(storageChaser);

            var storageScavenger = new StorageScavenger(db, readIndex);

            _outputBus.Subscribe <SystemMessage.ScavengeDatabase>(storageScavenger);

            //TCP
            var tcpService = new TcpService(MainQueue, _tcpEndPoint);

            Bus.Subscribe <SystemMessage.SystemInit>(tcpService);
            Bus.Subscribe <SystemMessage.SystemStart>(tcpService);
            Bus.Subscribe <SystemMessage.BecomeShuttingDown>(tcpService);

            //HTTP
            _httpService = new HttpService(ServiceAccessibility.Private, MainQueue, vNodeSettings.HttpPrefixes);
            Bus.Subscribe <SystemMessage.SystemInit>(HttpService);
            Bus.Subscribe <SystemMessage.BecomeShuttingDown>(HttpService);
            Bus.Subscribe <HttpMessage.SendOverHttp>(HttpService);
            Bus.Subscribe <HttpMessage.UpdatePendingRequests>(HttpService);
            HttpService.SetupController(new AdminController(MainQueue));
            HttpService.SetupController(new PingController());
            HttpService.SetupController(new StatController(monitoringQueue));
            HttpService.SetupController(new ReadEventDataController(MainQueue));
            HttpService.SetupController(new AtomController(MainQueue));
            HttpService.SetupController(new WebSiteController(MainQueue));

            //REQUEST MANAGEMENT
            var requestManagement = new RequestManagementService(MainQueue, 1, 1);

            Bus.Subscribe <StorageMessage.CreateStreamRequestCreated>(requestManagement);
            Bus.Subscribe <StorageMessage.WriteRequestCreated>(requestManagement);
            Bus.Subscribe <StorageMessage.TransactionStartRequestCreated>(requestManagement);
            Bus.Subscribe <StorageMessage.TransactionWriteRequestCreated>(requestManagement);
            Bus.Subscribe <StorageMessage.TransactionCommitRequestCreated>(requestManagement);
            Bus.Subscribe <StorageMessage.DeleteStreamRequestCreated>(requestManagement);
            Bus.Subscribe <StorageMessage.RequestCompleted>(requestManagement);
            Bus.Subscribe <StorageMessage.AlreadyCommitted>(requestManagement);
            Bus.Subscribe <StorageMessage.CommitAck>(requestManagement);
            Bus.Subscribe <StorageMessage.PrepareAck>(requestManagement);
            Bus.Subscribe <StorageMessage.WrongExpectedVersion>(requestManagement);
            Bus.Subscribe <StorageMessage.InvalidTransaction>(requestManagement);
            Bus.Subscribe <StorageMessage.StreamDeleted>(requestManagement);
            Bus.Subscribe <StorageMessage.PreparePhaseTimeout>(requestManagement);
            Bus.Subscribe <StorageMessage.CommitPhaseTimeout>(requestManagement);

            var clientService = new ClientService();

            Bus.Subscribe <TcpMessage.ConnectionClosed>(clientService);
            Bus.Subscribe <ClientMessage.SubscribeToStream>(clientService);
            Bus.Subscribe <ClientMessage.UnsubscribeFromStream>(clientService);
            Bus.Subscribe <ClientMessage.SubscribeToAllStreams>(clientService);
            Bus.Subscribe <ClientMessage.UnsubscribeFromAllStreams>(clientService);
            Bus.Subscribe <StorageMessage.EventCommited>(clientService);

            //TIMER
            //var timer = new TimerService(new TimerBasedScheduler(new RealTimer(), new RealTimeProvider()));
            _timerService = new TimerService(new ThreadBasedScheduler(new RealTimeProvider()));
            Bus.Subscribe <TimerMessage.Schedule>(TimerService);

            MainQueue.Start();
            monitoringQueue.Start();
        }
Exemplo n.º 44
0
 public AbstractROMTest()
 {
     this.bus = new Bus();
     this.cpu = bus.GetCPU();
 }
Exemplo n.º 45
0
        public Result Initialize(RunDescriptor run, EndpointBehavior endpointBehavior,
                                 IDictionary <Type, string> routingTable, string endpointName)
        {
            try
            {
                runDescriptor   = run;
                behavior        = endpointBehavior;
                scenarioContext = run.ScenarioContext;
                configuration   =
                    ((IEndpointConfigurationFactory)Activator.CreateInstance(endpointBehavior.EndpointBuilderType))
                    .Get();
                configuration.EndpointName = endpointName;

                if (!string.IsNullOrEmpty(configuration.CustomMachineName))
                {
                    RuntimeEnvironment.MachineNameAction = () => configuration.CustomMachineName;
                }

                //apply custom config settings
                var busConfiguration = configuration.GetConfiguration(run, routingTable);

                scenarioContext.ContextPropertyChanged += scenarioContext_ContextPropertyChanged;

                endpointBehavior.CustomConfig.ForEach(customAction => customAction(busConfiguration));

                if (configuration.SendOnly)
                {
                    sendOnlyBus = Bus.CreateSendOnly(busConfiguration);
                }
                else
                {
                    bus = Bus.Create(busConfiguration);
                    var transportDefinition = ((UnicastBus)bus).Settings.Get <TransportDefinition>();

                    scenarioContext.HasNativePubSubSupport = transportDefinition.HasNativePubSubSupport;
                }


                executeWhens = Task.Factory.StartNew(() =>
                {
                    while (!stopped)
                    {
                        //we spin around each 5s since the callback mechanism seems to be shaky
                        contextChanged.Wait(TimeSpan.FromSeconds(5));

                        lock (behavior)
                        {
                            foreach (var when in behavior.Whens)
                            {
                                if (executedWhens.Contains(when.Id))
                                {
                                    continue;
                                }

                                if (when.ExecuteAction(scenarioContext, bus))
                                {
                                    executedWhens.Add(when.Id);
                                }
                            }
                        }
                    }
                });

                return(Result.Success());
            }
            catch (Exception ex)
            {
                Logger.Error("Failed to initialize endpoint " + endpointName, ex);
                return(Result.Failure(ex));
            }
        }
Exemplo n.º 46
0
 public ButtonInterrupt(uint baseAddress, uint size, Bus addressBus, Bus dataBus, string name)
     : base(baseAddress, size, addressBus, dataBus, name)
 {
 }
Exemplo n.º 47
0
 public Customer(Bus bus, Waiter water, Cashier cashier)
 {
     _bus     = bus;
     _water   = water;
     _cashier = cashier;
 }
Exemplo n.º 48
0
 public AlarmClock(Bus bus)
 {
     _bus = bus;
 }
Exemplo n.º 49
0
 protected LittleEndianProcessor(Bus memory)
     : base(memory)
 {
 }
Exemplo n.º 50
0
 public FOGSystemService() : base()
 {
     Bus.SetMode(Bus.Mode.Server);
 }
Exemplo n.º 51
0
        static void Main(string[] args)
        {
            //First set of test code
            var tollCalc = new TollCalculator();
            var car      = new Car();
            var taxi     = new Taxi();
            var bus      = new Bus();
            var truck    = new DeliveryTruck();

            Console.WriteLine($"The toll for a car is {tollCalc.CalculateToll(car)}");
            Console.WriteLine($"The toll for a taxi is {tollCalc.CalculateToll(taxi)}");
            Console.WriteLine($"The toll for a bus is {tollCalc.CalculateToll(bus)}");
            Console.WriteLine($"The toll for a truck is {tollCalc.CalculateToll(truck)}");
            try
            {
                tollCalc.CalculateToll("this will fail");
            }
            catch (ArgumentException e)
            {
                Console.WriteLine("Caught an argument exception when using the wrong type");
            }
            try
            {
                tollCalc.CalculateToll(null !);
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("Caught an argument exception when using null");
            }


            /*  2nd test (after adding for occupants)
             * var tollCalc = new TollCalculator();
             * var soloDriver = new Car();
             * var twoRideShare = new Car { Passengers = 1 };
             * var threeRideShare = new Car { Passengers = 2 };
             * var fullVan = new Car { Passengers = 5 };
             * var emptyTaxi = new Taxi();
             * var singleFare = new Taxi { Fares = 1 };
             * var doubleFare = new Taxi { Fares = 2 };
             * var fullVanPool = new Taxi { Fares = 5 };
             * var lowOccupantBus = new Bus { Capacity = 90, Riders = 15 };
             * var normalBus = new Bus { Capacity = 90, Riders = 75 };
             * var fullBus = new Bus { Capacity = 90, Riders = 85 };
             * var heavyTruck = new DeliveryTruck { GrossWeightClass = 7500 };
             * var truck = new DeliveryTruck { GrossWeightClass = 4000 };
             * var lightTruck = new DeliveryTruck { GrossWeightClass = 2500 };
             * Console.WriteLine($"The toll for a solo driver is {tollCalc.CalculateToll(soloDriver)}");
             * Console.WriteLine($"The toll for a two ride share is {tollCalc.CalculateToll(twoRideShare)}");
             * Console.WriteLine($"The toll for a three ride share is {tollCalc.CalculateToll(threeRideShare)}");
             * Console.WriteLine($"The toll for a fullVan is {tollCalc.CalculateToll(fullVan)}");
             * Console.WriteLine($"The toll for an empty taxi is {tollCalc.CalculateToll(emptyTaxi)}");
             * Console.WriteLine($"The toll for a single fare taxi is {tollCalc.CalculateToll(singleFare)}");
             * Console.WriteLine($"The toll for a double fare taxi is {tollCalc.CalculateToll(doubleFare)}");
             * Console.WriteLine($"The toll for a full van taxi is {tollCalc.CalculateToll(fullVanPool)}");
             * Console.WriteLine($"The toll for a low-occupant bus is {tollCalc.CalculateToll(lowOccupantBus)}");
             * Console.WriteLine($"The toll for a regular bus is {tollCalc.CalculateToll(normalBus)}");
             * Console.WriteLine($"The toll for a bus is {tollCalc.CalculateToll(fullBus)}");
             * Console.WriteLine($"The toll for a truck is {tollCalc.CalculateToll(heavyTruck)}");
             * Console.WriteLine($"The toll for a truck is {tollCalc.CalculateToll(truck)}");
             * Console.WriteLine($"The toll for a truck is {tollCalc.CalculateToll(lightTruck)}");
             * try
             * {
             *  tollCalc.CalculateToll("this will fail");
             * }
             * catch (ArgumentException e)
             * {
             *  Console.WriteLine("Caught an argument exception when using the wrong type");
             * }
             * try
             * {
             *  tollCalc.CalculateToll(null);
             * }
             * catch (ArgumentNullException e)
             * {
             *  Console.WriteLine("Caught an argument exception when using null");
             * }
             */

            /*
             * Console.WriteLine("Testing the time premiums");
             * var testTimes = new DateTime[]
             * {
             *  new DateTime(2019, 3, 4, 8, 0, 0), // morning rush
             *  new DateTime(2019, 3, 6, 11, 30, 0), // daytime
             *  new DateTime(2019, 3, 7, 17, 15, 0), // evening rush
             *  new DateTime(2019, 3, 14, 03, 30, 0), // overnight
             *  new DateTime(2019, 3, 16, 8, 30, 0), // weekend morning rush
             *  new DateTime(2019, 3, 17, 14, 30, 0), // weekend daytime
             *  new DateTime(2019, 3, 17, 18, 05, 0), // weekend evening rush
             *  new DateTime(2019, 3, 16, 01, 30, 0), // weekend overnight
             * };
             * foreach (var time in testTimes)
             * {
             *  Console.WriteLine($"Inbound premium at {time} is {tollCalc.PeakTimePremiumFull(time, true)}");
             *  Console.WriteLine($"Outbound premium at {time} is {tollCalc.PeakTimePremiumFull(time, false)}");
             * }
             * Console.WriteLine("====================================================");
             * foreach (var time in testTimes)
             * {
             *  Console.WriteLine($"Inbound premium at {time} is {tollCalc.PeakTimePremium(time, true)}");
             *  Console.WriteLine($"Outbound premium at {time} is {tollCalc.PeakTimePremium(time, false)}");
             * }
             */
        }
Exemplo n.º 52
0
        public override void Execute(CPUState state, Bus bus)
        {
            int effectiveAddress = CalculateEffectiveAddress(state, bus);

            bus.Write(effectiveAddress, state.RegisterY);
        }
Exemplo n.º 53
0
 public void TheSubscriptionIsCreatedInEachRegion()
 {
     Bus.Received(2).AddNotificationSubscriber(Arg.Any <string>(), Arg.Any <INotificationSubscriber>());
 }
Exemplo n.º 54
0
 public void HandlerIsAddedToBus()
 {
     Bus.Received().AddMessageHandler(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <Func <IHandlerAsync <Message> > >());
 }
Exemplo n.º 55
0
        public async Task Should_be_received()
        {
            await Bus.Publish(new SomethingHappened { Caption = "System Screw Up" });

            await _observer.Received;
        }
Exemplo n.º 56
0
        public void Should_return_a_wonderful_breakdown_of_the_guts_inside_it()
        {
            var result = Bus.GetProbeResult();

            Console.WriteLine(result.ToJsonString());
        }
Exemplo n.º 57
0
 public void Handle(Message1 message)
 {
     logger.Info("Hello from MySaga");
     MarkAsComplete();
     Bus.SendLocal(new Message2());
 }
Exemplo n.º 58
0
 public TestCharacteristic(Bus bus, int index, ObjectPath service) : base(bus, index, testCharacteristicUUID, flags, service)
 {
     AddDescriptor(new TestDescriptor(bus, 0, GetPath()));
     data = new byte[0];
 }
Exemplo n.º 59
0
 public void Handle(ShipOrderResponse message)
 {
     Bus.Publish <OrderShipped>(e => e.OrderId = Data.OrderId);
     MarkAsComplete();
 }
Exemplo n.º 60
0
            public void Handle(StartSaga1Message message)
            {
                var sendFromSagaMessage = new SendFromSagaMessage();

                Bus.SendLocal(sendFromSagaMessage);
            }