Пример #1
0
        public void All_event_handling_doesnt_handle_handled_events()
        {
            var  source         = new EventJournalSource();
            var  journal        = new EventJournal(source);
            bool handlerInvoked = false;

            source.Publish(new SpeechRequestedEvent("some text"));

            journal
            .When <SpeechRequestedEvent>(e => handlerInvoked = true)
            .All();

            handlerInvoked.Should().BeTrue();

            handlerInvoked = false;
            journal
            .When <SpeechRequestedEvent>(e => handlerInvoked = true)
            .All();

            handlerInvoked.Should().BeFalse();
        }
Пример #2
0
        public void When_awaiting_any_of_two_events_Then_executes_when_action_of_first_received_event()
        {
            ConcurrencyTester.Run(() =>
            {
                var source                          = new EventJournalSource();
                var journal                         = new EventJournal(source);
                var executedEvent                   = new AutoResetEvent(false);
                QuestArrowEvent receivedQuest       = null;
                SpeechRequestedEvent receivedSpeech = null;

                var task = Task.Run(() =>
                {
                    journal
                    .When <QuestArrowEvent>(e =>
                    {
                        receivedQuest = e;
                        executedEvent.Set();
                    })
                    .When <SpeechRequestedEvent>(e =>
                    {
                        receivedSpeech = e;
                        executedEvent.Set();
                    })
                    .WaitAny();
                });

                journal.AwaitingStarted.AssertWaitOneSuccess();

                source.Publish(new SpeechRequestedEvent("some message"));

                executedEvent.AssertWaitOneSuccess();

                receivedQuest.Should().BeNull();
                receivedSpeech.Should().NotBeNull();
                receivedSpeech.Message.Should().Be("some message");
            });
        }
Пример #3
0
        public void First_satisfied_conditional_when_is_executed()
        {
            bool conditionalWhenExecuted     = false;
            bool notSatisfiedConditionalWhen = false;
            bool unconditionalWhenExecuted   = false;
            var  source  = new EventJournalSource();
            var  journal = new EventJournal(source);

            var task = Task.Run(() =>
            {
                journal
                .When <SpeechRequestedEvent>(e => e.Message == "I don't handle this message", e =>
                {
                    notSatisfiedConditionalWhen = true;
                })
                .When <SpeechRequestedEvent>(e => e.Message == "I handle this message", e =>
                {
                    conditionalWhenExecuted = true;
                })
                .When <SpeechRequestedEvent>(e =>
                {
                    unconditionalWhenExecuted = true;
                })
                .WaitAny();
            });

            journal.AwaitingStarted.AssertWaitOneSuccess();

            source.Publish(new SpeechRequestedEvent("something else than I refuse this message"));

            task.AssertWaitFastSuccess();

            unconditionalWhenExecuted.Should().BeTrue();
            conditionalWhenExecuted.Should().BeFalse();
            notSatisfiedConditionalWhen.Should().BeFalse();
        }
Пример #4
0
        public void Publish_after_WaitAny_doesnt_influence_next_call_to_WaitAny()
        {
            var    source  = new EventJournalSource();
            var    journal = new EventJournal(source);
            string result  = string.Empty;

            var task = Task.Run(() =>
            {
                journal
                .When <ContainerOpenedEvent>(e => result = "y")
                .When <SpeechReceivedEvent>(e => e.Speech.Message == "qwer", e => { result = "x"; })
                .WaitAny();
            });

            journal.AwaitingStarted.WaitOne(100).Should().BeTrue();
            source.Publish(new SpeechReceivedEvent(new JournalEntry(1, "qwer", "qwer", 0, 0)));
            task.Wait(100).Should().BeTrue();
            result.Should().Be("x");

            source.Publish(new SpeechReceivedEvent(new JournalEntry(1, "qwer", "qwer", 0, 0)));

            result = "z";
            task   = Task.Run(() =>
            {
                journal
                .When <ContainerOpenedEvent>(e => result = "y")
                .When <SpeechReceivedEvent>(e => e.Speech.Message == "qwer", e => { result = "x"; })
                .WaitAny();
            });

            journal.AwaitingStarted.WaitOne(100).Should().BeTrue();
            source.Publish(new ContainerOpenedEvent(1));

            task.Wait(100).Should().BeTrue();
            result.Should().Be("y");
        }
Пример #5
0
        public IEventStoreConnection Build()
        {
            if (m_configuration == null)
            {
                m_configuration = new EventStoreConnectionConfiguration();
                m_configure(m_configuration);

                m_configuration.AssertConfigurationCompleted();
                m_factory = new StorageFactory();
            }

            var connectivityState = new EventStoreConnectionState();

            var journalTable = new EventJournalTable(m_factory.CreateTable(
                                                         m_configuration.StorageConnectionString,
                                                         m_configuration.JournalTableName));

            var deploymentTable = m_factory.CreateTable(
                m_configuration.StorageConnectionString,
                m_configuration.EventStoreDeploymentTableName);

            var sessionFactory = new EventStreamConsumingSessionFactory(
                m_factory.CreateBlobContainer(
                    m_configuration.StorageConnectionString,
                    m_configuration.StreamConsumerSessionsBlobContainerName));

            var pipelineFactory = new EventMutationPipelineFactory(
                m_configuration.IncomingMessageMutators,
                m_configuration.OutgoingMessageMutators);

            var queues = Enumerable
                         .Range(0, m_configuration.NotificationQueuePartitionCount)
                         .Select(index => m_factory.CreateQueue(
                                     m_configuration.StorageConnectionString,
                                     m_configuration.NotificationQueueName + "-" + index.ToString("D3")))
                         .ToArray();

            var eventJournal = new EventJournal(journalTable);

            var consumersRegistry = new EventStreamConsumers(deploymentTable);
            var consumersService  = new ConsumersService(consumersRegistry, eventJournal);

            var notificationHub = new NotificationHub(
                new PollingJob("NotificationHubPollingJob", new PollingTimeout()),
                new NotificationsChannel(queues, new NotificationFormatter()),
                new ReceivedNotificationProcessor());

            var pendingNotificationTable          = m_factory.CreateTable(m_configuration.StorageConnectionString, m_configuration.PendingNotificationsTableName);
            var pendingNotifications              = new PendingNotifications(pendingNotificationTable);
            var pendingNotificationsChaserTimeout = new PollingTimeout(
                TimeSpan.FromMinutes(Constants.Settings.PENDING_NOTIFICATIONS_CHASER_INITIAL_TIMEOUT_IN_MINUTES),
                Constants.Settings.PENDING_NOTIFICATIONS_CHASER_TIMEOUT_MULTIPLIER,
                Constants.Settings.PENDING_NOTIFICATIONS_CHASER_TIMEOUT_INCREASING_THRESHOLD,
                TimeSpan.FromMinutes(Constants.Settings.PENDING_NOTIFICATIONS_CHASER_MAX_TIMEOUT_IN_MINUTES));

            var pendingNotificationsChaser = new PendingNotificationsChaser(
                pendingNotifications,
                notificationHub,
                new PollingJob("PendingNotificationsChaserPollingJob", pendingNotificationsChaserTimeout),
                m_factory.CreateBlobContainer(
                    m_configuration.StorageConnectionString,
                    m_configuration.PendingNotificationsChaserExclusiveAccessLockBlobContainerName).CreateBlockBlob(
                    m_configuration.PendingNotificationsChaserExclusiveAccessLockBlobName));

            connectivityState.ConnectionCreated += (sender, args) =>
            {
                if (m_configuration.BackgroundProcessingEnabled)
                {
                    foreach (var notificationListener in m_configuration.NotificationListeners)
                    {
                        notificationHub.Subscribe(notificationListener);
                    }

                    notificationHub.StartNotificationProcessing(args.Connection);
                    pendingNotificationsChaser.Start();
                }
            };

            connectivityState.ConnectionClosing += (sender, args) =>
            {
                if (m_configuration.BackgroundProcessingEnabled)
                {
                    notificationHub.StopNotificationProcessing();
                    pendingNotificationsChaser.Stop();
                }
            };

            connectivityState.ConnectionClosed += (sender, args) =>
            {
                if (m_configuration.BackgroundProcessingEnabled)
                {
                    foreach (var notificationListener in m_configuration.NotificationListeners)
                    {
                        notificationHub.Unsubscribe(notificationListener);
                    }
                }
            };

            return(new EventStoreConnection(
                       connectivityState,
                       eventJournal,
                       notificationHub,
                       pendingNotifications,
                       consumersRegistry,
                       sessionFactory,
                       pipelineFactory,
                       consumersService));
        }
Пример #6
0
 public Walker(Legacy api)
 {
     this.api     = api;
     this.journal = api.CreateEventJournal();
 }
Пример #7
0
 protected EventDispatcher(string journalName, string messageBusName, string topicName)
 {
     Journal = EventJournal.Open(journalName);
     Topic   = MessageBus.Start(messageBusName).OpenTopic(topicName);
     StartDispatching();
 }
Пример #8
0
 public EventSourceProposalRepository()
 {
     _eventJournal = EventJournal.Open("TalkWithMe-Matching");
 }
        private void runReporttoolStripButton_Click(object sender, EventArgs e)
        {
            Supplier s         = (Supplier)supplierkryptonComboBox.SelectedItem;
            bool     allStatus = statuskryptonComboBox2.Text == "ALL";
            bool     status    = true;

            if (!allStatus)
            {
                status = Boolean.Parse(statuskryptonComboBox2.Text);
            }
            string type = trtypekryptonComboBox1.Text;

            IList trs = r_sup.GetAllTransactions(s.ID, startdateKryptonDateTimePicker.Value, enDatekryptonDateTimePicker1.Value,
                                                 allStatus, status);

            transactionkryptonDataGridView.Rows.Clear();
            if (trs.Count > 0)
            {
                foreach (object ev in trs)
                {
                    if (ev is Event)
                    {
                        Event t = (Event)ev;
                        if (type != "ALL")
                        {
                            if (t.STOCK_CARD_ENTRY_TYPE.ToString() != type)
                            {
                                continue;
                            }
                        }
                        int r = transactionkryptonDataGridView.Rows.Add();
                        transactionkryptonDataGridView[datetrColumn.Index, r].Value = t.TRANSACTION_DATE;
                        transactionkryptonDataGridView[typeTrColumn.Index, r].Value = t.STOCK_CARD_ENTRY_TYPE.ToString();
                        transactionkryptonDataGridView[codeTrColumn.Index, r].Value = t.CODE;
                        transactionkryptonDataGridView[postedColumn.Index, r].Value = t.POSTED.ToString();
                        Supplier sup = (Supplier)r_sup.GetById((Supplier)t.VENDOR);
                        Employee emp = (Employee)r_emp.GetById(t.EMPLOYEE);
                        transactionkryptonDataGridView[supplierColumn.Index, r].Value   = sup.NAME;
                        transactionkryptonDataGridView[supCodeColumn.Index, r].Value    = sup.CODE;
                        transactionkryptonDataGridView[supAddressColumn.Index, r].Value = sup.ADDRESS;
                        transactionkryptonDataGridView[employeeColumn.Index, r].Value   = emp.CODE;
                        if (t is PurchaseOrder)
                        {
                            PurchaseOrder p = (PurchaseOrder)t;
                            p.TOP      = (TermOfPayment)r_top.GetById(p.TOP);
                            p.CURRENCY = (Currency)r_ccy.GetById(p.CURRENCY);
                            transactionkryptonDataGridView[topColumn.Index, r].Value    = p.TOP.CODE;
                            transactionkryptonDataGridView[amountColumn.Index, r].Value = p.NET_TOTAL;
                            transactionkryptonDataGridView[ccyColumn.Index, r].Value    = p.CURRENCY.CODE;
                        }
                        if (t is SupplierInvoice)
                        {
                            SupplierInvoice p = (SupplierInvoice)t;
                            p.TOP      = (TermOfPayment)r_top.GetById(p.TOP);
                            p.CURRENCY = (Currency)r_ccy.GetById(p.CURRENCY);
                            transactionkryptonDataGridView[topColumn.Index, r].Value    = p.TOP.CODE;
                            transactionkryptonDataGridView[amountColumn.Index, r].Value = p.NET_TOTAL;
                            transactionkryptonDataGridView[ccyColumn.Index, r].Value    = p.CURRENCY.CODE;
                        }
                    }
                    if (ev is EventJournal)
                    {
                        EventJournal t = (EventJournal)ev;
                        if (type != "ALL")
                        {
                            if (t.VENDOR_BALANCE_ENTRY_TYPE.ToString() != type)
                            {
                                continue;
                            }
                        }
                        int r = transactionkryptonDataGridView.Rows.Add();
                        transactionkryptonDataGridView[datetrColumn.Index, r].Value = t.TRANSACTION_DATE;
                        transactionkryptonDataGridView[typeTrColumn.Index, r].Value = t.VENDOR_BALANCE_ENTRY_TYPE.ToString();
                        transactionkryptonDataGridView[codeTrColumn.Index, r].Value = t.CODE;
                        transactionkryptonDataGridView[postedColumn.Index, r].Value = t.POSTED.ToString();
                        Supplier sup = (Supplier)r_sup.GetById((Supplier)t.VENDOR);
                        Employee emp = (Employee)r_emp.GetById(t.EMPLOYEE);
                        transactionkryptonDataGridView[supplierColumn.Index, r].Value   = sup.NAME;
                        transactionkryptonDataGridView[supCodeColumn.Index, r].Value    = sup.CODE;
                        transactionkryptonDataGridView[supAddressColumn.Index, r].Value = sup.ADDRESS;
                        transactionkryptonDataGridView[employeeColumn.Index, r].Value   = emp.CODE;
                        if (t is Payment)
                        {
                            Payment p = (Payment)t;
                            p.CURRENCY = (Currency)r_ccy.GetById(p.CURRENCY);
                            transactionkryptonDataGridView[amountColumn.Index, r].Value = p.NET_AMOUNT;
                            transactionkryptonDataGridView[ccyColumn.Index, r].Value    = p.CURRENCY.CODE;
                        }
                        if (t is SupplierOutStandingInvoice)
                        {
                            SupplierOutStandingInvoice p = (SupplierOutStandingInvoice)t;
                            p.CURRENCY = (Currency)r_ccy.GetById(p.CURRENCY);
                            transactionkryptonDataGridView[amountColumn.Index, r].Value = p.NET_AMOUNT;
                            transactionkryptonDataGridView[ccyColumn.Index, r].Value    = p.CURRENCY.CODE;
                        }
                        if (t is APDebitNote)
                        {
                            APDebitNote p = (APDebitNote)t;
                            p.CURRENCY = (Currency)r_ccy.GetById(p.CURRENCY);
                            transactionkryptonDataGridView[amountColumn.Index, r].Value = p.NET_AMOUNT;
                            transactionkryptonDataGridView[ccyColumn.Index, r].Value    = p.CURRENCY.CODE;
                        }
                    }
                }
            }
        }
Пример #10
0
 public EventSourceTutorRepository()
 {
     _eventJournal = EventJournal.Open("TalkWithMe-Tutor");
 }
Пример #11
0
 public ObjectNameReceiver(Legacy api)
 {
     this.api = api;
     journal  = api.CreateEventJournal();
 }
Пример #12
0
        internal static bool Initialize()
        {
            try
            {
                Journal = new EventJournal();
                Journal.Open(Settings.Default.DisableLogDB ? String.Empty : Settings.Default.LogsDatabasePath, Settings.Default.DBOptionsLogs,
                             String.Format(Settings.Default.LogsTracePathTemplate, DateTime.Now.ToString(CultureInfo.CurrentCulture).Replace('/', '_').Replace(':', '_')),
                             Settings.Default.ForceLogFlush,
                             Settings.Default.IncludeDetailsInLog);
                Journal.AppendLog(ComplexParts.Service, LogMessageType.Info, Resources.Log_SystemHost_Application_started);
            }
            catch (Exception ex)
            {
                File.AppendAllText(@"SCME.Service error.txt",
                                   $"\n\n{DateTime.Now}\nEXCEPTION: {ex}\nINNER EXCEPTION: {ex.InnerException ?? new Exception("No additional information - InnerException is null")}\n");

                return(false);
            }

//            try
//            {
//                SQLiteDatabaseService dbForMigration = new SQLiteDatabaseService(Settings.Default.ResultsDatabasePath);
//                dbForMigration.Open();
//                dbForMigration.Migrate();
//                dbForMigration.Close();
//            }
//            catch (Exception ex)
//            {
//                Journal.AppendLog(ComplexParts.Service, LogMessageType.Warning, String.Format("Migrate database error: {0}", ex.Message));
//                return false;
//            }

            try
            {
                Results = new ResultsJournal();
                ///??
                //Results.Open(Settings.Default.DisableResultDB ? String.Empty : Settings.Default.ResultsDatabasePath, Settings.Default.DBOptionsResults, Settings.Default.MMECode);
                Results.Open(Settings.Default.ResultsDatabasePath, Settings.Default.DBOptionsResults, Settings.Default.MMECode);

                if (!Settings.Default.IsLocal)
                {
                    Journal.AppendLog(ComplexParts.Service, LogMessageType.Info, Resources.Log_SystemHost_Result_journal_opened);
                }

                //нам ещё не известно как завершится процесс синхронизации данных, поэтому
                IsSyncedWithServer = null;

//                switch (Settings.Default.IsLocal)
//                {
//                    case true:
//                        //синхронизация отключена, уведомляем UI, что стадия синхронизации баз данных пройдена
//                        AfterSyncWithServerRoutineHandler("Synchronization of the local database with a central database is prohibited by parameter DisableResultDB");
//                        break;
//
//                    default:
//                        //запускаем в потоке синхронизацию результатов измерений и профилей
//                        Results.SyncWithServer(AfterSyncWithServerRoutineHandler);
//                        break;
//                }

                try
                {
                    ms_ControlService     = new ExternalControlServer();
                    ms_ControlServiceHost = new ServiceHost(ms_ControlService);
                    ms_ControlServiceHost.Open();
                    Journal.AppendLog(ComplexParts.Service, LogMessageType.Info, String.Format(Resources.Log_SystemHost_Control_service_is_listening));

                    ms_DatabaseServiceHost = new ServiceHost(typeof(DatabaseServer));

                    HostDbService();
                }
                catch (Exception ex)
                {
                    File.AppendAllText(@"SCME.Service error.txt",
                                       $"\n\n{DateTime.Now}\nEXCEPTION: {ex}\nINNER EXCEPTION: {ex.InnerException ?? new Exception("No additional information - InnerException is null")}\n");
                    Journal.AppendLog(ComplexParts.Service, LogMessageType.Warning, $"SQLite database error: {ex?.InnerException?.ToString() ?? ex.ToString()}");
                    return(false);
                }


                try
                {
                    ms_DatabaseServiceHost.AddServiceEndpoint(typeof(IDatabaseCommunicationService), new NetTcpBinding("DefaultTcpBinding"), Settings.Default.DBServiceExternalEndpoint);
                }
                catch (Exception ex)
                {
                    Journal.AppendLog(ComplexParts.Service, LogMessageType.Warning, String.Format("Can't open external database service port: {0}", ex.Message));
                }

                ms_DatabaseServiceHost.Open();
                Journal.AppendLog(ComplexParts.Service, LogMessageType.Info, String.Format(Resources.Log_SystemHost_Database_service_is_listening));

                ms_MaintenanceServiceHost = new ServiceHost(typeof(MaintenanceServer));

                try
                {
                    ms_MaintenanceServiceHost.AddServiceEndpoint(typeof(IDatabaseMaintenanceService), new NetTcpBinding("DefaultTcpBinding"), Settings.Default.MaintenanceServiceExternalEndpoint);
                }
                catch (Exception ex)
                {
                    Journal.AppendLog(ComplexParts.Service, LogMessageType.Warning, String.Format("Can't open external maintenance service port: {0}", ex.Message));
                }

                ms_MaintenanceServiceHost.Open();
                Journal.AppendLog(ComplexParts.Service, LogMessageType.Info, String.Format(Resources.Log_SystemHost_Maintenance_service_is_listening));

                return(true);
            }
            catch (Exception ex)
            {
                File.AppendAllText(@"SCME.Service error.txt",
                                   $"\n\n{DateTime.Now}\nEXCEPTION: {ex}\nINNER EXCEPTION: {ex.InnerException ?? new Exception("No additional information - InnerException is null")}\n");
                Journal.AppendLog(ComplexParts.Service, LogMessageType.Error, ex.Message);
                Journal.Close();
                return(false);
            }
        }
 internal JournalProposalRepository()
 {
     this.journal = EventJournal.Open("donebyme-matching");
     this.reader  = this.journal.StreamReader();
 }
Пример #14
0
 public static void Start()
 {
     eventJournal = EventJournal.Open("donebyme-matching");
 }
Пример #15
0
 public EventSourceTutorRecommendationRepository()
 {
     _eventJournal = EventJournal.Open("TalkWithMe-Profile");
 }
 internal JournalPricingAnalysisRepository()
 {
     this.journal = PricingJournal.EventJournal;
     this.reader  = this.journal.StreamReader();
 }
Пример #17
0
 internal PersonRepository()
 {
     this.journal = EventJournal.Open("repo-test");
     this.reader  = this.journal.StreamReader();
 }
Пример #18
0
        private bool SaveEventJournals(DockingStationEvent dsEvent, DateTime lastDockedTime, DataAccessTransaction trx)
        {
            if (dsEvent.EventCode == null)
            {
                return(true);
            }

            EventJournalDataAccess ejDataAccess = new EventJournalDataAccess();

            EventJournal eventJournal = null;

            // If the event implements IPassed, then use the result of its
            // Passed property.  Otherwise, just default to true.
            bool passed = ((dsEvent is IPassed)) ? ((IPassed)dsEvent).Passed : true;

            if (dsEvent is InstrumentEvent)
            {
                // special case for // bump & cals... need to save a separate
                // event journal for every sensor involved in gas operation.
                // Note that in this situation, we also do NOT save an entry for the instrument itself.
                if (dsEvent is InstrumentGasResponseEvent && !(dsEvent is InstrumentManualOperationsDownloadEvent))
                {
                    InstrumentGasResponseEvent gasResponseTestEvent = (InstrumentGasResponseEvent)dsEvent;
                    if (gasResponseTestEvent.GasResponses.Count <= 0)
                    {
                        return(true);
                    }

                    bool allSaved = true;
                    foreach (SensorGasResponse sgr in gasResponseTestEvent.GasResponses)
                    {
                        eventJournal = new EventJournal(gasResponseTestEvent.EventCode.Code, sgr.Uid,
                                                        gasResponseTestEvent.DockedInstrument.SerialNumber,
                                                        sgr.Time, dsEvent.Time, sgr.Passed,
                                                        sgr.Position, gasResponseTestEvent.DockedInstrument.SoftwareVersion);
                        allSaved &= ejDataAccess.Save(eventJournal, trx);
                    }
                    // If gasResponseEvent is a InstrumentBumpTestEvent, it might have calibration gas responses due to O2 high bump test failure.
                    // If there are any gas responses in HighBumpFailCalGasResponses, store them to the event journals.
                    foreach (SensorGasResponse sgr in gasResponseTestEvent.HighBumpFailCalGasResponses)
                    {
                        eventJournal = new EventJournal(EventCode.Calibration, sgr.Uid,
                                                        gasResponseTestEvent.DockedInstrument.SerialNumber,
                                                        sgr.Time, dsEvent.Time, sgr.Passed,
                                                        sgr.Position, gasResponseTestEvent.DockedInstrument.SoftwareVersion);
                        allSaved &= ejDataAccess.Save(eventJournal, trx);
                    }
                    return(allSaved);
                }
                else
                {
                    eventJournal = new EventJournal(dsEvent.EventCode, ((InstrumentEvent)dsEvent).DockedInstrument.SerialNumber, dsEvent.Time, dsEvent.Time, passed, ((InstrumentEvent)dsEvent).DockedInstrument.SoftwareVersion);
                }
            }
            else // DockingStationEvent
            {
                eventJournal = new EventJournal(dsEvent.EventCode, dsEvent.DockingStation.SerialNumber, dsEvent.Time, dsEvent.Time, passed, dsEvent.DockingStation.SoftwareVersion);
            }

            return(ejDataAccess.Save(eventJournal, trx));  // Update/insert EventJournal record for the event.
        }