Beispiel #1
1
        private static void RegisterCommands(Container container)
        {
            var eventDelegator = new EventBus();
            var eventStore = new EventStore(eventDelegator);
            var aggregateFactory = new AggregateFactory();
            var commandProcessor = new CommandProcessor(aggregateFactory, eventStore);

            container.RegisterSingleton<IProcessCommands>(() => commandProcessor);
        }
 public AppWindowViewModel()
 {
    _eventBus = new EventBus();
    _viewModels = new IViewModel[]
                         {
                            new LaunchViewModel(_eventBus),
                            new ExecuteViewModel(_eventBus),
                            new SettingsViewModel(_eventBus)
                         };
    ContentViewModel = new Observable<IContentViewModel>();
 }
        private void AddFileWritingListenerIfConfigured(EventBus bus)
        {
            if (string.IsNullOrEmpty(_settings.OutputFileFormat))
                return;

            if (string.IsNullOrEmpty(_settings.OutputFile))
                return;

            var outputFile = _settings.OutputFile;

            var fileWriter = new FileWriter(outputFile, true);

            switch (_settings.OutputFileFormat.ToLower())
            {
                case "xml":

                    bus.Register(new XmlReportListener(fileWriter));
                    break;
                case "spark":
                    bus.Register(new SparkReportListener(fileWriter, _settings.OutputFileTemplate));
                    break;
                default:
                    throw new ConfigurationErrorsException(
                        string.Format("'{0} is not a valid output file format.'", _settings.OutputFileFormat));
            }
        }
        static void Main(string[] args)
        {
            EventBus bus = new EventBus();
            _eventStore = new MemoryEventStore(bus);

            IEventSourcedRepository<Column> eventSourcedRepository = UseSnapshotting
                ? CreateSnapshottingRepository(EventsPerSnapshot)
                : CreateNonSnapshottingRepository();

            ColumnCommandHandler commandHandler = new ColumnCommandHandler(eventSourcedRepository);
            _columnRepository = new MemoryRepository<ColumnDTO>();
            _calculationRepository = new MemoryRepository<CalculationDTO>();
            ColumnView columnView = new ColumnView(_columnRepository);
            CalculationView calculationView = new CalculationView(_calculationRepository);

            //bus.Subscribe<IEvent>(ev => _log.Information("New Event: {@Event}", ev));

            bus.Subscribe<ColumnCreated>(columnView.Handle);
            bus.Subscribe<ColumnRenamed>(columnView.Handle);
            bus.Subscribe<ColumnDataTypeChanged>(columnView.Handle);
            bus.Subscribe<ColumnMadePrimary>(columnView.Handle);
            bus.Subscribe<ColumnPrimaryCleared>(columnView.Handle);
            bus.Subscribe<CalculationAdded>(columnView.Handle);
            bus.Subscribe<CalculationRemoved>(columnView.Handle);

            bus.Subscribe<CalculationAdded>(calculationView.Handle);
            bus.Subscribe<CalculationRemoved>(calculationView.Handle);
            bus.Subscribe<CalculationOperandChanged>(calculationView.Handle);
            bus.Subscribe<CalculationOperatorChanged>(calculationView.Handle);

            PerformSomeActions(commandHandler);
            ShowReadModel();

            PerformLotsOfActions(commandHandler);
        }
        public void SetUp()
        {
            persistentConnection = MockRepository.GenerateStub<IPersistentConnection>();
            channel = MockRepository.GenerateStub<IModel>();
            var eventBus = new EventBus();
            var configuration = new ConnectionConfiguration();

            var shutdownArgs = new ShutdownEventArgs(
                ShutdownInitiator.Peer, 
                AmqpException.ConnectionClosed,
                "connection closed by peer");
            var exception = new OperationInterruptedException(shutdownArgs);
            var first = true;

            persistentConnection.Stub(x => x.CreateModel()).WhenCalled(x =>
                {
                    if (first)
                    {
                        first = false;
                        throw exception;
                    }
                    x.ReturnValue = channel;
                });

            var logger = MockRepository.GenerateStub<IEasyNetQLogger>();

            persistentChannel = new PersistentChannel(persistentConnection, logger, configuration, eventBus);

            new Timer(_ => eventBus.Publish(new ConnectionCreatedEvent())).Change(10, Timeout.Infinite);

            persistentChannel.InvokeChannelAction(x => x.ExchangeDeclare("MyExchange", "direct"));
        }
        public void SetUp()
        {
            //var logger = new ConsoleLogger();
            var logger = MockRepository.GenerateStub<IEasyNetQLogger>();
            var consumerErrorStrategy = MockRepository.GenerateStub<IConsumerErrorStrategy>();
            var eventBus = new EventBus();

            handlerRunner = new HandlerRunner(logger, consumerErrorStrategy, eventBus);

            Func<byte[], MessageProperties, MessageReceivedInfo, Task> userHandler = (body, properties, info) => 
                Task.Factory.StartNew(() =>
                    {
                        deliveredBody = body;
                        deliveredProperties = properties;
                        deliveredInfo = info;
                    });

            var consumer = MockRepository.GenerateStub<IBasicConsumer>();
            channel = MockRepository.GenerateStub<IModel>();
            consumer.Stub(x => x.Model).Return(channel).Repeat.Any();

            var context = new ConsumerExecutionContext(
                userHandler, messageInfo, messageProperties, messageBody, consumer);

            var autoResetEvent = new AutoResetEvent(false);
            eventBus.Subscribe<AckEvent>(x => autoResetEvent.Set());

            handlerRunner.InvokeUserMessageHandler(context);

            autoResetEvent.WaitOne(1000);
        }
Beispiel #7
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            gameConfiguration = new GameConfiguration("config.xml");
            if (gameConfiguration.fullscreen)
            {
                graphics.ToggleFullScreen();
                graphics.PreferredBackBufferWidth = 1920;
                graphics.PreferredBackBufferHeight = 1080;

            }
            else
            {
                graphics.PreferredBackBufferWidth = 1024;
                graphics.PreferredBackBufferHeight = 768;
            }

            graphics.ApplyChanges();

            Window.Title = "MinGH";
            IsMouseVisible = true;
            FlatRedBallServices.InitializeFlatRedBall(this, graphics);
            ScreenManager.Start(typeof(MainMenu).FullName);

            // Feels sloppy, but is how event listeners/handlers are set
            EventBus<ScreenChange>.EventHandler screenChange =
                new EventBus<ScreenChange>.EventHandler(ChangeGameState);
            EventBus<ScreenChange>.instance.Event += screenChange;

            base.Initialize();
        }
    public static EventBus GetInstance()
    {
        if (instance == null)
            instance = new EventBus();

        return instance;
    }
Beispiel #9
0
        public MailWindow(EventBus eventBus)
        {
            _eventBus = eventBus;
            InitializeComponent();

            Unloaded += UnloadedHandler;
            MessageWebView.Navigated += MessageWebViewOnNavigated;
        }
Beispiel #10
0
    private Suburbia()
    {
        m_eventBus = new EventBus ();

        m_eventBus.AddHandler(EventEndOfTurn.TYPE, this);
        m_eventBus.AddHandler(EventLastTurn.TYPE, this);
        m_eventBus.AddHandler(EventEndOfGame.TYPE, this);
    }
Beispiel #11
0
        protected void BeforeAll()
        {
            _eventBus = StorEvilEvents.Bus;

            _storyContext = TestSession.SessionContext(GetType().Assembly.Location).GetContextForStory();
            _interpreter = new StandardScenarioInterpreter();
            _scenarioLineExecuter = new ScenarioLineExecuter(_interpreter, _eventBus);
        }
Beispiel #12
0
        public async void Throws_An_Exception_If_A_Null_Event_Data_Is_Provided_Asynchronously()
        {
            // Arrange
            var publicationStrategyMock = new Mock<IPublicationStrategy>();
            var sut = new EventBus(publicationStrategyMock.Object);

            // Act/Assert
            await Assert.ThrowsAsync<ArgumentNullException>(() => sut.PublishAsync((object)null));
        }
Beispiel #13
0
 public FinalizeService(EventBus bus)
 {
     _bus = bus;
     InstanceCounter++;
     _bus.OnNext(new EventModel
     {
         Message = $"Create finalize service instance (counter {InstanceCounter})",
         EventType = this.GetType()
     });
 }
 public void SetUp()
 {
     var logger = new ConsoleLogger();
     var eventBus = new EventBus();
     var parser = new ConnectionStringParser();
     var configuration = parser.Parse("host=localhost");
     var hostSelectionStrategy = new RandomClusterHostSelectionStrategy<ConnectionFactoryInfo>();
     var connectionFactory = new ConnectionFactoryWrapper(configuration, hostSelectionStrategy);
     connection = new PersistentConnection(connectionFactory, logger, eventBus);
     persistentChannel = new PersistentChannel(connection, logger, configuration, new EventBus());
 }
      public LaunchViewModel(EventBus eventBus)
      {
         _eventBus = eventBus;

         Path = new Observable<string>();
         History = new ObservableCollection<SolutionSettings.HistoryItem>();
         BrowseCommand = new RelayCommand(Browse);
         CreateSolutionCommand = new RelayCommand(CreateSolution, CanCreateSolution);
         ConfigureExistingCommand = new RelayCommand<SolutionSettings.HistoryItem>(ConfigureExisting);
         ExecuteExistingCommand = new RelayCommand<SolutionSettings.HistoryItem>(RunExisting);
      }
        public void TestHandlersForAChildClassShouldNotBeCalledWhenParentClassIsSent()
        {
            var eventBus = new EventBus();
            var testMessage = new EmptyTestMessage();

            eventBus.Register((ChildEmptyTestMessage message) => {
                throw new Exception("Handlers for a class should not be called when messages of a parent class are sent");
            });

            eventBus.Send(testMessage);
        }
            public void tryingToRaiseAnEvent()
            {
                var bus = new EventBus();

                bus.specificSubscriber += subscribingMethod;

                var @event = new MyEvent();
                bus.publish(@event);

                @event.SubscriberWasCalled.Should().BeTrue();
            }
      public SettingsViewModel(EventBus eventBus)
      {
         _eventBus = eventBus;

         Fixie = new Observable<FixieViewModel>();
         MsBuild = new Observable<MsBuildViewModel>();
         Projects = new Observable<IEnumerable<ProjectViewModel>>();
         Visible = new Observable<bool>();

         AcceptCommand = new RelayCommand(Accept);
         CancelCommand = new RelayCommand(Cancel);
      }
        public void SetUp()
        {
            var eventBus = new EventBus();
            var logger = new ConsoleLogger();
            var parser = new ConnectionStringParser();
            var configuration = parser.Parse("host=localhost");
            var hostSelectionStrategy = new DefaultClusterHostSelectionStrategy<ConnectionFactoryInfo>();
            var connectionFactory = new ConnectionFactoryWrapper(configuration, hostSelectionStrategy);
            connection = new PersistentConnection(connectionFactory, logger, eventBus);
            var persistentChannelFactory = new PersistentChannelFactory(logger, configuration, eventBus);

            dispatcher = new ClientCommandDispatcher(connection, persistentChannelFactory);
        }
Beispiel #20
0
 public ApplicationWorker(AccountsSettingsModel accountsSettings, 
     EventBus eventBus, 
     OutgoingMailServiceResolver serviceResolver, 
     AsyncObservableCollection<EmailGroupModel> emailGroupList,
     ApplicationSettingsModel appSettings,
     IMailStorage mailStorage)
 {
     _accountsSettings = accountsSettings;
     _eventBus = eventBus;
     _serviceResolver = serviceResolver;
     _emailGroupList = emailGroupList;
     _appSettings = appSettings;
     _mailStorage = mailStorage;
 }
        public void SetUpListeners(EventBus bus)
        {
            if (_settings.ConsoleMode != ConsoleMode.Quiet)
            {
                var consoleListener = new ConsoleResultListener
                {
                    ColorEnabled = _settings.ConsoleMode == ConsoleMode.Color
                };

                bus.Register(consoleListener);
            }

            AddFileWritingListenerIfConfigured(bus);
        }
        public MailListWindow(EventBus eventBus, AsyncObservableCollection<EmailGroupModel> emailGroupList, ApplicationSettingsModel appSettings)
        {
            _eventBus = eventBus;
            _emailGroupListModel = emailGroupList;
            _appSettings = appSettings;

            var screen = Screen.FromHandle(new WindowInteropHelper(this).Handle).WorkingArea;
            _defaultWindowRect = new Rect(screen.Width - DefaultWidth, 0, DefaultWidth, screen.Height);

            InitializeComponent();
            SetWindowRect();
            Closing += OnClosing;
            _emailGroupListModel.CollectionChanged += EmailGroupListModelOnCollectionChanged;
        }
        public RemoteScenarioExecutor(IRemoteTaskServer server, AssemblyRegistry assemblyRegistry)
        {
            _server = server;
            _assemblyRegistry = assemblyRegistry;
            _sessionContext = new SessionContext(assemblyRegistry);

            _eventBus = new EventBus();
            _listener = new ResharperResultListener(_server);

            _resolver = new MostRecentlyUsedContext();
            _runner = BuildInPlaceRunner(_resolver);

            _eventBus.Register(_resolver);
            _eventBus.Register(_listener);
        }
        public void TestHandlersForABaseClassShouldReceiveDerivedClassMessages()
        {
            var eventBus = new EventBus();
            var testMessage = new ChildEmptyTestMessage();

            bool handlerCalled = false;

            eventBus.Register((EmptyTestMessage message) => {
                message.Should().BeSameAs(testMessage, "because we should have received the object we sent");
                handlerCalled = true;
            });

            eventBus.Send(testMessage);

            handlerCalled.Should().BeTrue("because handlers registered for a base class should receive derived class messages");
        }
Beispiel #25
0
        private static void RegisterQueries(Container container)
        {
            var eventDelegator = new EventBus();

            var reservationHub = new Lazy<IHubContext>(() => GlobalHost.ConnectionManager.GetHubContext<ReservationHub>());

            var getAllReservationsView = new GetAllReservationsView();
            var getAllReservationsViewDecorator = new GetAllReservationsViewHub(reservationHub, getAllReservationsView);

            container.RegisterSingleton<IGetAllReservationsView>(() => { return getAllReservationsViewDecorator; });

            eventDelegator.Register<ReservationCreated>(getAllReservationsViewDecorator.Handle);
            eventDelegator.Register<ReservationOutboundDateTimeChanged>(getAllReservationsViewDecorator.Handle);
            eventDelegator.Register<ReservationDeleted>(getAllReservationsViewDecorator.Handle);

            eventDelegator.StartListener();
        }
Beispiel #26
0
        public async void Uses_The_Provided_Strategies_To_Publish_An_Event_Asynchronously()
        {
            // Arrange
            var publicationStrategyMock = new[]
            {
                new Mock<IPublicationStrategy>(),
                new Mock<IPublicationStrategy>(),
                new Mock<IPublicationStrategy>()
            };
            var sut = new EventBus(publicationStrategyMock.Select(m => m.Object));

            // Act
            await sut.PublishAsync("some data");

            // Assert
            publicationStrategyMock[0].Verify(s => s.Publish("some data"));
            publicationStrategyMock[1].Verify(s => s.Publish("some data"));
            publicationStrategyMock[2].Verify(s => s.Publish("some data"));
        }
        public void TestCorrectMessageIsReceived()
        {
            var eventBus = new EventBus();
            var testMessage = new EmptyTestMessage();

            bool handlerCalled = false;

            eventBus.Register((EmptyTestMessage message) => {
                message.Should().BeSameAs(testMessage, "because we should have received the object we sent");
                handlerCalled = true;
            });

            eventBus.Register((EmptyTestMessage2 message) => {
                throw new Exception("Handler should not be called");
            });

            eventBus.Send(testMessage);
            handlerCalled.Should().BeTrue("because otherwise the correct handler wasn't called");
        }
        public RemoteScenarioExecutor(IRemoteTaskServer server, AssemblyRegistry assemblyRegistry)
        {
            _server = server;
            _assemblyRegistry = assemblyRegistry;
            _sessionContext = new SessionContext(assemblyRegistry);

            _eventBus = new EventBus();

            new EventBusAutoRegistrar(_assemblyRegistry).InstallTo(_eventBus);
            _listener = new ResharperResultListener(_server);

            _resolver = new MostRecentlyUsedContext();
            _runner = BuildInPlaceRunner(_resolver);

            _eventBus.Register(_resolver);
            _eventBus.Register(_listener);

            ParameterConverter.AddCustomConverters(_assemblyRegistry);
        }
        public UserAccountService(MembershipRebootConfiguration configuration, IUserAccountRepository userRepository)
        {
            if (configuration == null) throw new ArgumentNullException("configuration");
            if (userRepository == null) throw new ArgumentNullException("userRepository");
            
            this.Configuration = configuration;

            var validationEventBus = new EventBus();
            validationEventBus.Add(new UserAccountValidator(this));
            this.userRepository = new EventBusUserAccountRepository(userRepository,
                new AggregateEventBus { validationEventBus, configuration.ValidationBus },
                configuration.EventBus);

            this.usernameValidator = new Lazy<AggregateValidator>(()=>
            {
                var val = new AggregateValidator();
                if (!this.SecuritySettings.EmailIsUsername)
                {
                    val.Add(UserAccountValidation.UsernameDoesNotContainAtSign);
                }
                val.Add(UserAccountValidation.UsernameMustNotAlreadyExist);
                val.Add(configuration.UsernameValidator);
                return val;
            });

            this.emailValidator = new Lazy<AggregateValidator>(() =>
            {
                var val = new AggregateValidator();
                val.Add(UserAccountValidation.EmailIsValidFormat);
                val.Add(UserAccountValidation.EmailMustNotAlreadyExist);
                val.Add(configuration.EmailValidator);
                return val;
            });

            this.passwordValidator = new Lazy<AggregateValidator>(() =>
            {
                var val = new AggregateValidator();
                val.Add(UserAccountValidation.PasswordMustBeDifferentThanCurrent);
                val.Add(configuration.PasswordValidator);
                return val;
            });
        }
Beispiel #30
0
 void OnEnable()
 {
     playerInteractHandler    = EventBus.Subscribe <PlayerInteractEvent>(OnPlayerInteracted);
     playerDisInteractHandler = EventBus.Subscribe <PlayerDisinteractEvent>(OnPlayerDisinteracted);
 }
Beispiel #31
0
 public void OnPointerEnter(PointerEventData eventData)
 {
     EventBus.Publish <AppleScoreEvent>(new AppleScoreEvent(score));
     Destroy(this.gameObject);
 }
Beispiel #32
0
 void OnDisable()
 {
     EventBus.Unsubscribe(playerInteractHandler);
     EventBus.Unsubscribe(playerDisInteractHandler);
 }
 public override void Apply()
 {
     Curio.AddBehavior(this);
     EventBus.Register(this);
 }
Beispiel #34
0
        public HomeModule(IDeezerApi deezerApi, ISongRepository songRepository,
                          IPlaylistRepository playlistRepository, Environment environment,
                          IMetric metric)
        {
            _deezerApi          = deezerApi;
            _songRepository     = songRepository;
            _playlistRepository = playlistRepository;
            _environment        = environment;
            _metric             = metric;
            var eventStream    = new MemoryEventStream();
            var eventPublisher = new EventBus(eventStream);

            eventPublisher.Subscribe(new PlaylistHandler(playlistRepository));

            Get["/"] = _ =>
            {
                using (var timer = _metric.Timer("home"))
                {
                    var model = new
                    {
                        appid   = _environment.AppId,
                        channel = _environment.Channel
                    };

                    return(View["index", model]);
                }
            };

            Get["/channel"] = _ =>
            {
                using (var timer = _metric.Timer("channel"))
                {
                    var cacheExpire = 60 * 60 * 24 * 365;

                    return(View["channel"]
                           .WithHeader("Pragma", "public")
                           .WithHeader("Cache-Control", $"maxage={cacheExpire}")
                           .WithHeader("Expires", DateTime.Now.AddMinutes(cacheExpire).ToString("F")));
                }
            };

            Post["/login"] = _ =>
            {
                using (var timer = _metric.Timer("createplaylist"))
                {
                    var model = this.Bind <LoginViewModel>();

                    var user = User.Create(eventStream, eventPublisher, _deezerApi, _songRepository,
                                           _playlistRepository, model.Email, model.Nickname, model.UserId, model.AccessToken,
                                           _environment.Size);

                    user.AddPlaylist(model.PlaylistName);
                    Console.WriteLine(user.Playlist.PlaylistId.Value);
                    return(Response.AsJson(new { playlistCreated = !user.Playlist.PlaylistId.IsEmpty }));
                }
            };

            Get["/canCreatePlaylist/{userId}"] = parameters =>
            {
                using (var timer = _metric.Timer("hasplaylist"))
                {
                    var userId            = UserId.Parse((string)parameters.userId);
                    var canCreatePlaylist = _playlistRepository
                                            .CanCreatePlaylist(userId, DateTime.UtcNow.AddDays(-1));

                    return(Response.AsJson(new { canCreatePlaylist }));
                }
            };
        }
Beispiel #35
0
 public override void apply()
 {
     EventBus.Publish <ClearTextStatus>(new ClearTextStatus {
         AssociatedAlgorithm = AssociatedAlgorithm
     });
 }
Beispiel #36
0
 void OnEnable()
 {
     EventBus.StartListening("Queso", Quesod);
 }
 /// <summary>
 /// 注册EventHandler
 /// </summary>
 public void RegisterEventHandler()
 {
     EventBus <GroupMemberApply> .Instance().After += new CommonEventHandler <GroupMemberApply, CommonEventArgs>(GroupMemberApplyNoticeModule_After);
 }
Beispiel #38
0
        public InfoReader() : base(PLUGIN_NAME, PLUGIN_AUTHOR)
        {
            if (!File.Exists("InfoReader.db"))
            {
                File.WriteAllBytes("InfoReader.db", Resource1.Database);
            }

            /*else
             * {
             *  byte[] dbBytes = File.ReadAllBytes("InfoReader.db");
             *  MD5 selfMd5 = MD5.Create(), fileMd5 = MD5.Create();
             *  selfMd5.ComputeHash(Resource1.Database);
             *  fileMd5.ComputeHash(dbBytes);
             *  MD5String selfMd5String = new MD5String(selfMd5), fileMd5String = new MD5String(fileMd5);
             *  if (selfMd5String != fileMd5String)
             *  {
             *      File.Delete("InfoReader.db");
             *      File.WriteAllBytes("InfoReader.db",Resource1.Database);
             *  }
             * }*/
            StringBuilder builder = new StringBuilder(32);

            GetPrivateProfileString("Sync.DefaultConfiguration", "Language", "zh-cn", builder, 32, "..\\config.ini");
            SyncLang     = builder.ToString();
            CurrentNi18N = NI18n.GetCurrentLanguage();
            CurrentNi18N.InitializeOperator();
            ScanCommand();
            if (File.Exists("RealTimePPDisplayer.dll"))
            {
                byte[] b = File.ReadAllBytes("RealTimePPDisplayer.dll");
                MD5    selfMd5 = MD5.Create(), fileMd5 = MD5.Create();
                selfMd5.ComputeHash(Resource1.ModifiedRealTimePPDisplayer);
                fileMd5.ComputeHash(b);
                if (MD5String.GetString(selfMd5) != MD5String.GetString(fileMd5))
                {
                    var dirInfo = Directory.CreateDirectory("..\\OrignalRealTimePPDisplayer\\");
                    IO.CurrentIO.Write(NI18n.GetLanguageElement("LANG_INFO_RTPPDREPLACED"));
                    if (File.Exists(Path.Combine(dirInfo.FullName, "RealTimePPDisplayer.dll")))
                    {
                        File.Delete(Path.Combine(dirInfo.FullName, "RealTimePPDisplayer.dll"));
                    }
                    File.Move("RealTimePPDisplayer.dll", Path.Combine(dirInfo.FullName, "RealTimePPDisplayer.dll"));
                    File.WriteAllBytes("RealTimePPDisplayer.dll", Resource1.ModifiedRealTimePPDisplayer);
                }
            }
            else
            {
                File.WriteAllBytes("RealTimePPDisplayer.dll", Resource1.ModifiedRealTimePPDisplayer);
            }

            /*if(!File.Exists("bass.dll"))
             *  File.WriteAllBytes("bass.dll",Resource1.bass);*/

            _outputInfoMap = MemoryMappedFile.CreateOrOpen("InfoReaderMmf", 128);
            EventBus.BindEvent <PluginEvents.InitPluginEvent>(Init);
            EventBus.BindEvent <PluginEvents.LoadCompleteEvent>(Loaded);
            EventBus.BindEvent <PluginEvents.InitCommandEvent>(CommandInit);
            PluginConfigurationManager manager = new Sync.Tools.PluginConfigurationManager(this);

            manager.AddItem(Setting);
        }
Beispiel #39
0
 void OnEnable()
 {
     EventBus.StartListening("Audio", AddAudioEvent);
 }
        private void TryProcessJob(BackgroundJobInfo jobInfo)
        {
            try
            {
                jobInfo.TryCount++;
                jobInfo.LastTryTime = DateTime.Now;

                var jobType = Type.GetType(jobInfo.JobType);
                using (var job = _iocResolver.ResolveAsDisposable(jobType))
                {
                    try
                    {
                        var jobExecuteMethod = job.Object.GetType().GetTypeInfo().GetMethod("Execute");
                        var argsType         = jobExecuteMethod.GetParameters()[0].ParameterType;
                        var argsObj          = JsonConvert.DeserializeObject(jobInfo.JobArgs, argsType);

                        jobExecuteMethod.Invoke(job.Object, new[] { argsObj });

                        AsyncHelper.RunSync(() => _store.DeleteAsync(jobInfo));
                    }
                    catch (Exception ex)
                    {
                        Logger.Warn(ex.Message, ex);

                        var nextTryTime = jobInfo.CalculateNextTryTime();
                        if (nextTryTime.HasValue)
                        {
                            jobInfo.NextTryTime = nextTryTime.Value;
                        }
                        else
                        {
                            jobInfo.IsAbandoned = true;
                        }

                        TryUpdate(jobInfo);

                        EventBus.Trigger(
                            this,
                            new ExceptionData(
                                new BackgroundJobException(
                                    "A background job execution is failed. See inner exception for details. See BackgroundJob property to get information on the background job.",
                                    ex
                                    )
                        {
                            BackgroundJob = jobInfo,
                            JobObject     = job.Object
                        }
                                )
                            );
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.ToString(), ex);

                jobInfo.IsAbandoned = true;

                TryUpdate(jobInfo);
            }
        }
 /// <summary>
 /// 注册事件处理程序
 /// </summary>
 void IEventMoudle.RegisterEventHandler()
 {
     EventBus <Journal, AuditEventArgs> .Instance().After += new CommonEventHandler <Journal, AuditEventArgs>(JournalsEventModule_After);
 }
Beispiel #42
0
 public void Clear()
 {
     _packetListener = new EventBus <BasePacket>();
     _eventListener  = new EventBus <IEvent>();
 }
Beispiel #43
0
 private void OnJointBreak(float breakForce)
 {
     EventBus.Trigger(EventHooks.OnJointBreak, gameObject, breakForce);
 }
Beispiel #44
0
 void OnEnable()
 {
     EventBus.StartListening("Stop", Stop);
 }
 /// <summary>
 /// 注册事件处理程序
 /// </summary>
 void IEventMoudle.RegisterEventHandler()
 {
     EventBus <BlogThread> .Instance().After += new CommonEventHandler <BlogThread, CommonEventArgs>(BlogOperationLogEventModule_After);
 }
 private void Awake()
 {
     m_Camera = Camera.main;
     AddDisposable(EventBus.Subscribe(this));
 }
 /// <summary>
 /// Trigger the return event. This is meant for internal use of the trigger unit.
 /// </summary>
 /// <param name="trigger">The trigger unit we will return to when it hits a return unit.</param>
 /// <param name="target">The gameobject target of the event</param>
 /// <param name="name">The name of the event.</param>
 /// <param name="global">Is the event global to all Return Events? Will ignore the target GameObject. Target can be null in this case.</param>
 /// <param name="args">The arguments to send through.</param>
 public static void Trigger(TriggerReturnEvent trigger, GameObject target, string name, bool global = false, params object[] args)
 {
     EventBus.Trigger <ReturnEventArg>("Return", new ReturnEventArg(trigger, target, name, global, args));
 }
Beispiel #48
0
 public void WaitUntilEventBusIsIdle()
 {
     EventBus.WaitForIdle();
     loggerTest.LogInformation("Waiting for the EventBus to become idle completed");
 }
Beispiel #49
0
 public CreateCompany(EventBus eventBus, ICompanyQueries companyQueries) : base(eventBus)
 {
     _companyQueries = companyQueries ?? throw new ArgumentNullException(nameof(companyQueries));
 }
        internal static bool Prefix(AddPet __instance)
        {
            if (!__instance.Owner.IsPlayerFaction)
            {
                return(true);
            }
            if (__instance.SpawnedPet == null)
            {
                return(false);
            }

            AddClassLevels component = __instance.SpawnedPet.Blueprint.GetComponent <AddClassLevels>();


            if (component == null)
            {
                return(false);
            }

            if (!manual_classes.Contains(component.CharacterClass))
            {//non animal and non eidolon companions will have automatic level up
                return(true);
            }

            int pet_level = 0;
            var eidolon   = __instance.SpawnedPet.Blueprint.GetComponent <Eidolon.EidolonComponent>();

            if (eidolon == null)
            {
                var tr = Harmony12.Traverse.Create(__instance);
                pet_level = tr.Method("GetPetLevel").GetValue <int>();
            }
            else
            {
                pet_level = eidolon.getEidolonLevel(__instance);
            }
            //Main.logger.Log("Pet level: " + __instance.SpawnedPet.Descriptor.Progression.CharacterLevel.ToString());
            //Main.logger.Log("Should be: " + pet_level.ToString());

            if (pet_level > __instance.SpawnedPet.Descriptor.Progression.CharacterLevel)
            {
                if (__instance.SpawnedPet.Descriptor.Progression.CharacterLevel == 0)
                {
                    component.LevelUp(__instance.SpawnedPet.Descriptor, 1);
                }
                var exp = Game.Instance.BlueprintRoot.Progression.XPTable.GetBonus(pet_level);
                Harmony12.Traverse.Create(__instance.SpawnedPet.Descriptor.Progression).Property("Experience").SetValue(exp);
                EventBus.RaiseEvent <IUnitGainExperienceHandler>((Action <IUnitGainExperienceHandler>)(h => h.HandleUnitGainExperience(__instance.SpawnedPet.Descriptor, exp)));
                //Main.logger.Log("Pet level now: " + __instance.SpawnedPet.Descriptor.Progression.CharacterLevel.ToString());
            }

            if (eidolon != null)
            {//no upgrade for eidolon, since they are performed through summoner
                return(false);
            }
            int?rank = __instance.Owner.GetFact((BlueprintUnitFact)__instance.LevelRank)?.GetRank();

            if (Mathf.Min(20, !rank.HasValue ? 0 : rank.Value) < __instance.UpgradeLevel)
            {
                return(false);
            }
            __instance.SpawnedPet.Descriptor.Progression.Features.AddFeature(__instance.UpgradeFeature, (MechanicsContext)null);
            return(false);
        }
Beispiel #51
0
 private static void FireEvent <T>(T @event) where T : DetourEvent
 {
     HookEvent(@event);
     EventBus.Fire(@event);
 }
 public static void Trigger(GameObject target, string name, Action <object> callback = null, bool global = false, params object[] args)
 {
     EventBus.Trigger <ReturnEventArg>("Return", new ReturnEventArg(callback, target, name, global, args));
 }
Beispiel #53
0
 private void OnMouseEnter()
 {
     EventBus.Trigger(EventHooks.OnMouseEnter, gameObject);
 }
        public override void RunAction()
        {
            UnitEntityData caster = this.Context.MaybeCaster;

            if (caster == null)
            {
                UberDebug.LogError((UnityEngine.Object) this, (object)"Caster is missing", (object[])Array.Empty <object>());
            }
            var unit = this.Target.Unit;

            if (unit == null || !unit.Descriptor.State.IsDead || unit.Descriptor.State.HasCondition(UnitCondition.Petrified))
            {
                return;
            }

            Rounds duration = this.DurationValue.Calculate(this.Context);

            int level   = Math.Max(Math.Min(getRacialHD(this.Target.Unit.Descriptor), 20), Blueprint.GetComponent <AddClassLevels>().Levels);
            int max_lvl = this.Context.Params.CasterLevel * hd_cl_multiplier * (this.Context.MaybeCaster.Descriptor.HasFact(ChannelEnergyEngine.desecrate_buff) ? 2 : 1);

            if (level > max_lvl)
            {
                Common.AddBattleLogMessage($"{unit.CharacterName} corpse HD ({level}) is beyond your {caster.CharacterName}'s to animate ({max_lvl}).");
                return;
            }

            //Main.logger.Log("Animate Dead: Remaining HD limit: " + getUsedHD(this.Context, SummonPool).ToString() + "/" + (this.Context.Params.CasterLevel * max_hd_cl_multiplier).ToString());
            int max_total_hd = this.Context.Params.CasterLevel * max_hd_cl_multiplier;
            int used_hd      = getUsedHD(this.Context, SummonPool);
            int remaining_hd = max_total_hd - used_hd;

            if (level > remaining_hd)
            {
                Common.AddBattleLogMessage($"{unit.CharacterName} corpse HD ({level}) does not fit into {caster.CharacterName}'s animate dead HD limit ({remaining_hd}/{max_total_hd})");
                return;
            }
            Vector3        clampedPosition = ObstacleAnalyzer.GetNearestNode(this.Target.Point).clampedPosition;
            UnitEntityView unitEntityView  = this.Blueprint.Prefab.Load(false);

            var target_size = unit.Descriptor.OriginalSize;

            float radius = !((UnityEngine.Object)unitEntityView != (UnityEngine.Object)null) ? 0.5f : unitEntityView.Corpulence;

            FreePlaceSelector.PlaceSpawnPlaces(1, radius, clampedPosition);

            Vector3        relaxedPosition = FreePlaceSelector.GetRelaxedPosition(0, true);
            UnitEntityData animated_unit   = this.Context.TriggerRule <RuleSummonUnit>(new RuleSummonUnit(caster, this.Blueprint, relaxedPosition, duration, 0)
            {
                Context           = this.Context,
                DoNotLinkToCaster = this.do_not_link_to_caster
            }).SummonedUnit;

            if (this.SummonPool != null)
            {
                GameHelper.RegisterUnitInSummonPool(this.SummonPool, animated_unit);
            }

            var level_up_component = animated_unit.Blueprint.GetComponent <AddClassLevels>();

            int current_level = level_up_component.Levels;

            animated_unit.Stats.Strength.BaseValue  = unit.Stats.Strength.BaseValue + str_bonus;
            animated_unit.Stats.Dexterity.BaseValue = unit.Stats.Dexterity.BaseValue + dex_bonus;

            if (adapt_size)
            {
                animated_unit.Descriptor.AddFact(Common.size_override_facts[target_size], null, null);
            }

            if (current_level < level)
            {
                level_up_component.LevelUp(animated_unit.Descriptor, level - current_level);
            }

            if (transfer_equipment && unit.Body.HandsAreEnabled)
            {
                animated_unit.Body.CurrentHandEquipmentSetIndex = unit.Body.CurrentHandEquipmentSetIndex;
                List <ItemSlot> list1 = unit.Body.EquipmentSlots.ToList <ItemSlot>();
                List <ItemSlot> list2 = animated_unit.Body.EquipmentSlots.ToList <ItemSlot>();
                for (int index = 0; index < list1.Count && index < list2.Count; ++index)
                {
                    ItemEntity maybeItem = list1[index].MaybeItem;
                    if (maybeItem != null)
                    {
                        animated_unit.Body.TryInsertItem(maybeItem.Blueprint, list2[index]);
                    }
                }
            }
            animated_unit.Descriptor.State.AddCondition(UnitCondition.Unlootable, (Kingmaker.UnitLogic.Buffs.Buff)null);


            using (this.Context.GetDataScope(animated_unit))
            {
                this.AfterSpawn.Run();
            }

            unit.Descriptor.AddFact(Common.no_animate_feature);

            animated_unit.Descriptor.CustomName = animated_unit.Descriptor.CharacterName + $" ({level} HD)";
            EventBus.RaiseEvent <IUnitNameHandler>((Action <IUnitNameHandler>)(h => h.OnUnitNameChanged(animated_unit)));
        }
 public override void Remove()
 {
     base.Remove();
     EventBus.Unregister(this);
 }
Beispiel #56
0
 /// <summary>
 /// 注册事件处理程序
 /// </summary>
 void IEventMoudle.RegisterEventHandler()
 {
     EventBus <MicroblogEntity> .Instance().After += new CommonEventHandler <MicroblogEntity, CommonEventArgs>(MicroblogOperationLogEventModule_After);
 }
 public void RegisterEventHandler()
 {
     EventBus <FollowEntity> .Instance().After += new CommonEventHandler <FollowEntity, CommonEventArgs>(FollowUser_After);
 }
Beispiel #58
0
 private void OnCinematicEnd(PlayableDirector director)
 {
     EventBus.PublishEvent(new FriendFullyAssembledEvent()); // This event kicks off the end credits
 }
Beispiel #59
0
 public Application(DependencyBundle dependencies)
 {
     EventBus = new EventBus(dependencies.EventStore);
     RegisterReactors(dependencies);
 }
Beispiel #60
-12
        private void AddFileWritingListenerIfConfigured(EventBus bus)
        {
            if (string.IsNullOrEmpty(_settings.OutputFile))
                return;

            bus.Register(GetWriterForOutputFormat());
        }