Represents an implementation of IEventProcessorthat processes the projection from an event.
Inheritance: IEventProcessor
Beispiel #1
0
        public void Should_be_able_to_get_round_robin_projections()
        {
            var processor = new EventProcessor(new Mock <IEventStoreConfiguration>().Object,
                                               new Mock <IPipelineFactory>().Object, new Mock <IProjectionRepository>().Object);

            processor.AddProjection("projection-1");
            processor.AddProjection("projection-2");

            var projection1 = processor.GetProjection();

            Assert.That(projection1, Is.Not.Null);

            var projection2 = processor.GetProjection();

            Assert.That(projection2, Is.Not.Null);

            Assert.That(processor.GetProjection(), Is.Null);

            processor.ReleaseProjection(projection1);

            Assert.That(processor.GetProjection(), Is.Not.Null);
            Assert.That(processor.GetProjection(), Is.Null);

            processor.ReleaseProjection(projection2);

            Assert.That(processor.GetProjection(), Is.Not.Null);
            Assert.That(processor.GetProjection(), Is.Null);

            Assert.That(() => processor.ReleaseProjection(new Projection("fail", 1)), Throws.TypeOf <InvalidOperationException>());
        }
Beispiel #2
0
        public void Should_be_able_to_place_projection_into_clustered_aggregation()
        {
            var configuration = new Mock <IEventStoreConfiguration>();

            configuration.Setup(m => m.ProjectionEventFetchCount).Returns(100);

            var projectionRepository = new Mock <IProjectionRepository>();

            projectionRepository.Setup(m => m.Find("projection-1")).Returns(new Projection("projection-1", 1));
            projectionRepository.Setup(m => m.Find("projection-2")).Returns(new Projection("projection-2", 300));
            projectionRepository.Setup(m => m.Find("projection-3")).Returns(new Projection("projection-3", 301));
            projectionRepository.Setup(m => m.Find("projection-4")).Returns(new Projection("projection-4", 600));

            var processor = new EventProcessor(configuration.Object,
                                               new Mock <IPipelineFactory>().Object, projectionRepository.Object);

            var projection1 = processor.AddProjection("projection-1");
            var projection2 = processor.AddProjection("projection-2");
            var projection3 = processor.AddProjection("projection-3");
            var projection4 = processor.AddProjection("projection-4");

            Assert.That(projection1.AggregationId, Is.EqualTo(projection2.AggregationId));
            Assert.That(projection3.AggregationId, Is.EqualTo(projection4.AggregationId));
            Assert.That(projection1.AggregationId, Is.Not.EqualTo(projection3.AggregationId));
        }
Beispiel #3
0
        static async Task Consume(string connectionString, string consumerGroup, string eventHubName)
        {
            await using (var client = new EventHubClient(connectionString, eventHubName))
            {
                Func <PartitionContext, CheckpointManager, IPartitionProcessor> partitionProcessorFactory =
                    (partitionContext, checkpointManager) => new TemperatureProcessor(partitionContext.PartitionId);

                var partitionManager = new InMemoryPartitionManager();

                var eventProcessorOptions = new EventProcessorOptions
                {
                    InitialEventPosition   = EventPosition.Latest,
                    MaximumReceiveWaitTime = TimeSpan.FromSeconds(1)
                };

                var eventProcessor = new EventProcessor(
                    consumerGroup,
                    client,
                    partitionProcessorFactory,
                    partitionManager,
                    eventProcessorOptions);

                await eventProcessor.StartAsync();

                Console.WriteLine("Receiving...");
                Console.ReadLine();
            }
        }
        public static Optimizely NewDefaultInstance(string sdkKey, string fallback)
        {
            var logger             = OptimizelyLogger ?? new DefaultLogger();
            var errorHandler       = new DefaultErrorHandler(logger, false);
            var eventDispatcher    = new DefaultEventDispatcher(logger);
            var builder            = new HttpProjectConfigManager.Builder();
            var notificationCenter = new NotificationCenter();

            var configManager = builder
                                .WithSdkKey(sdkKey)
                                .WithDatafile(fallback)
                                .WithLogger(logger)
                                .WithErrorHandler(errorHandler)
                                .WithNotificationCenter(notificationCenter)
                                .Build(true);

            EventProcessor eventProcessor = null;

#if !NETSTANDARD1_6 && !NET35
            eventProcessor = new BatchEventProcessor.Builder()
                             .WithLogger(logger)
                             .WithMaxBatchSize(MaxEventBatchSize)
                             .WithFlushInterval(MaxEventFlushInterval)
                             .WithEventDispatcher(eventDispatcher)
                             .WithNotificationCenter(notificationCenter)
                             .Build();
#endif

            return(NewDefaultInstance(configManager, notificationCenter, eventDispatcher, errorHandler, logger, eventProcessor: eventProcessor));
        }
Beispiel #5
0
        public void TestInitialize()
        {
            ea  = new EventAccess();
            ep  = new EventProcessor();
            eca = new EventCharacterAccess();
            ecp = new EventCharacterProcessor();

            string   eventName             = "Test Raid";
            string   eventType             = "Raid";
            string   location              = "266,070";
            DateTime date                  = new DateTime(2020, 12, 10, 12, 0, 0);
            string   description           = "Doing a full raid. Be available for at least 2 hours";
            int      maxNumberOfCharacters = 25;
            string   guildID               = "99999999-9999-9999-9999-999999999999";

            testEvent = new Event(guildID, eventName, description, eventType, location, date, maxNumberOfCharacters);

            string characterName = "Bob";
            string race          = "Demon";
            string gender        = "Both";
            string profession    = "Janitor";
            int    level         = 95;
            string guild         = "A guild";
            int    age           = 900;
            string created       = "Yes";
            int    deaths        = 1;
            string title         = "Title";

            testCharacter = new Character(characterName, race, gender, profession, level, guild, age, created, deaths, title);

            ep.InsertEvent(testEvent.Name, testEvent.EventType, testEvent.Location,
                           testEvent.Date, testEvent.Description, testEvent.MaxNumberOfCharacters, testEvent.GuildID);
            testEvent.EventID = ea.GetIdOfEvent(testEvent.Name);
        }
Beispiel #6
0
        public void WorkItem_addNew_succeeds()
        {
            var logger   = new DebugEventLogger();
            var settings = TestHelpers.LoadConfigFromResourceFile("NewObjects.policies", logger);

            var repository = new WorkItemRepositoryMock();

            var context = Substitute.For <IRequestContext>();

            context.GetProjectCollectionUri().Returns(
                new System.Uri("http://*****:*****@"C:\WorkItem_addNew_succeeds", settings, context, logger, (c, i, l) => repository);

            var parent = new WorkItemMock(repository, runtime);

            parent.Id       = 1;
            parent.TypeName = "Bug";
            parent[CoreFieldReferenceNames.Title]       = "My bug #1";
            parent[CoreFieldReferenceNames.TeamProject] = "MyTeamProject";

            repository.SetWorkItems(new[] { parent });

            using (var processor = new EventProcessor(runtime))
            {
                var notification = Substitute.For <INotification>();
                notification.WorkItemId.Returns(1);

                var result = processor.ProcessEvent(context, notification);

                Assert.AreEqual(0, result.ExceptionProperties.Count);
                Assert.AreEqual(1, repository.LoadedWorkItems.Count);
                Assert.AreEqual(1, repository.CreatedWorkItems.Count);
            }
        }
Beispiel #7
0
 public void Initialize(IEnumerable<Event> events)
 {
     store = new InMemoryEventStore(events);
       repository = new InMemoryRepository();
       eventProcessor = new EventProcessor(store, repository);
       commandProcessor = new CommandProcessor(repository, eventProcessor);
 }
Beispiel #8
0
        public void Should_be_able_to_place_projection_into_clustered_aggregation()
        {
            var configuration = new Mock <IEventStoreConfiguration>();

            configuration.Setup(m => m.ProjectionEventFetchCount).Returns(100);

            var processor = new EventProcessor(configuration.Object,
                                               new Mock <IPipelineFactory>().Object, new Mock <IProjectionRepository>().Object);

            var projection1 = new Projection("projection-1", 1, Environment.MachineName,
                                             AppDomain.CurrentDomain.BaseDirectory);
            var projection2 = new Projection("projection-2", 300, Environment.MachineName,
                                             AppDomain.CurrentDomain.BaseDirectory);

            var projection3 = new Projection("projection-3", 301, Environment.MachineName,
                                             AppDomain.CurrentDomain.BaseDirectory);
            var projection4 = new Projection("projection-4", 600, Environment.MachineName,
                                             AppDomain.CurrentDomain.BaseDirectory);

            processor.AddProjection(projection1);
            processor.AddProjection(projection2);
            processor.AddProjection(projection3);
            processor.AddProjection(projection4);

            Assert.That(projection1.AggregationId, Is.EqualTo(projection2.AggregationId));
            Assert.That(projection3.AggregationId, Is.EqualTo(projection4.AggregationId));
            Assert.That(projection1.AggregationId, Is.Not.EqualTo(projection3.AggregationId));
        }
Beispiel #9
0
    // Load scripts
    void InitializeScripts()
    {
        // --- Web sockets
        serverInterface = new ServerInterface();
        serverInterface.Initialize();

        // --- Interfaces
        List<UIBase> interfaces = new List<UIBase>();

        // Dashboard
        UIBase dashboard = interfaceObject.GetComponent<DashboardUI>();
        dashboard.Initialize();
        interfaces.Add(dashboard);

        // Facebook
        UIBase facebookPanel = interfaceObject.GetComponent<FacebookPanel>();
        dashboard.Initialize();
        interfaces.Add(dashboard);

        activeInterfaces = interfaces.ToArray();

        // --- Events
        eventProcessor = eventProcessorObject.GetComponent<EventProcessor>();
        eventProcessor.Initialize();

        // --- Get main page content
        //Debug.Log("pinging server for content....");
    }
Beispiel #10
0
        public void Should_aggregate_to_parent_should_handle_null()
        {
            var logger              = Substitute.For <ILogEvents>();
            var settings            = TestHelpers.LoadConfigFromResourceFile("Rollup.policies", logger);
            var alternateRepository = new WorkItemRepositoryMock();

            var grandParent = new WorkItemMock(alternateRepository);

            grandParent.Id               = 1;
            grandParent.TypeName         = "Feature";
            grandParent["Dev Estimate"]  = null;
            grandParent["Test Estimate"] = null;

            var parent = new WorkItemMock(alternateRepository);

            parent.Id       = 2;
            parent.TypeName = "Use Case";
            parent.WorkItemLinks.Add(new WorkItemLinkMock("Parent", 1, alternateRepository));
            grandParent.WorkItemLinks.Add(new WorkItemLinkMock("Child", 2, alternateRepository));
            parent["Total Work Remaining"] = 3.0D;
            parent["Total Estimate"]       = 4.0D;

            var child = new WorkItemMock(alternateRepository);

            child.Id       = 3;
            child.TypeName = "Task";
            child.WorkItemLinks.Add(new WorkItemLinkMock("Parent", 2, alternateRepository));
            parent.WorkItemLinks.Add(new WorkItemLinkMock("Child", 3, alternateRepository));
            child["Estimated Dev Work"]  = 10.0D;
            child["Estimated Test Work"] = 20.0D;
            child["Remaining Dev Work"]  = null;
            child["Remaining Test Work"] = 2.0D;
            child["Finish Date"]         = new DateTime(2015, 1, 1);

            child.WorkItemLinks.Add(new WorkItemLinkMock(WorkItemImplementationBase.ParentRelationship, parent.Id, alternateRepository));
            parent.WorkItemLinks.Add(new WorkItemLinkMock(WorkItemImplementationBase.ParentRelationship, grandParent.Id, alternateRepository));
            alternateRepository.SetWorkItems(new[] { grandParent, parent, child });

            var context = Substitute.For <IRequestContext>();

            context.GetProjectCollectionUri().Returns(
                new System.Uri("http://localhost:8080/tfs/DefaultCollection"));
            var runtime = RuntimeContext.MakeRuntimeContext("settingsPath", settings, context, logger, (c, i, l) => alternateRepository);

            using (var processor = new EventProcessor(runtime))
            {
                var notification = Substitute.For <INotification>();
                notification.WorkItemId.Returns(3);

                var result = processor.ProcessEvent(context, notification);

                Assert.AreEqual(0, result.ExceptionProperties.Count());
                Assert.IsFalse(child.InternalWasSaveCalled);
                Assert.IsTrue(parent.InternalWasSaveCalled);
                Assert.IsFalse(grandParent.InternalWasSaveCalled);
                Assert.AreEqual(2.0D, parent["Total Work Remaining"]);
                Assert.AreEqual(30.0D, parent["Total Estimate"]);
                Assert.AreEqual(EventNotificationStatus.ActionPermitted, result.NotificationStatus);
            }
        }
Beispiel #11
0
        partial void OnCreateContainer(UnityContainer container)
        {
            var serializer = container.Resolve <ITextSerializer>();
            var metadata   = container.Resolve <IMetadataProvider>();

            container.RegisterType <IBlobStorage, SqlBlobStorage>(new ContainerControlledLifetimeManager(), new InjectionConstructor("Conference"));

            var commandBus = new CommandBus(new MessageSender("SqlBus", "SqlBus.Commands"), serializer);
            var eventBus   = new EventBus(new MessageSender("SqlBus", "SqlBus.Events"), serializer);

            var commandProcessor = new CommandProcessor(new MessageReceiver("SqlBus", "SqlBus.Commands"), serializer);
            var eventProcessor   = new EventProcessor(new MessageReceiver("SqlBus", "SqlBus.Events"), serializer);

            container.RegisterInstance <ICommandBus>(commandBus);
            container.RegisterInstance <IEventBus>(eventBus);
            container.RegisterInstance <ICommandHandlerRegistry>(commandProcessor);
            container.RegisterInstance <IProcessor>("CommandProcessor", commandProcessor);
            container.RegisterInstance <IEventHandlerRegistry>(eventProcessor);
            container.RegisterInstance <IProcessor>("EventProcessor", eventProcessor);

            // Event log database and handler.
            container.RegisterType <SqlMessageLog>(new InjectionConstructor("Conference", serializer, metadata));
            container.RegisterType <IEventHandler, SqlMessageLogHandler>("SqlMessageLogHandler");
            container.RegisterType <ICommandHandler, SqlMessageLogHandler>("SqlMessageLogHandler");

            RegisterRepository(container);
            RegisterEventHandlers(container, eventProcessor);
            RegisterCommandHandlers(container);
        }
Beispiel #12
0
 public AbstractGameLevel(ServerMgr serverMgr)
 {
     mgr     = serverMgr;
     objects = new List <ISceneObject>();
     events  = new EventProcessor();
     CreateLevelObjects();
 }
        public async Task Events_should_be_processed(EventData[] eventsData)
        {
            var clientMock            = new Mock <IDurableOrchestrationClient>();
            var documentCollectorMock = new Mock <IAsyncCollector <SagaItem> >();
            var loggerMock            = new Mock <ILogger>();

            clientMock
            .Setup(x => x.RaiseEventAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(Task.CompletedTask);

            documentCollectorMock
            .Setup(x => x.AddAsync(It.IsAny <SagaItem>(), default))
            .Returns(Task.CompletedTask);

            await EventProcessor
            .SagaEventProcessor(eventsData, documentCollectorMock.Object, clientMock.Object, loggerMock.Object);

            int expectedClientExecutionTimes    = CountEvents;
            int expectedCollectorExecutionTimes = CountEvents;

            clientMock
            .Verify(x => x.RaiseEventAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()), Times.Exactly(expectedClientExecutionTimes));

            documentCollectorMock
            .Verify(x => x.AddAsync(It.IsAny <SagaItem>(), default), Times.Exactly(expectedCollectorExecutionTimes));
        }
Beispiel #14
0
        public Task <IEventProcessCore> Init(EventProcessor eventProcessor)
        {
            this._eventProcessor = eventProcessor;
            IEventProcessCore eventProcessCore = this;

            return(Task.FromResult(eventProcessCore));
        }
Beispiel #15
0
        /// <summary>
        /// Called by the ManyConsole framework to execute the  <i>run</i> command.
        /// </summary>
        /// <param name="remainingArguments">Unparsed command line arguments.</param>
        /// <returns>0 for success, error code otherwise</returns>
        public override int Run(string[] remainingArguments)
        {
            // cache requires absolute path
            this.PolicyFile = System.IO.Path.GetFullPath(this.PolicyFile);

            // need a logger to show errors in config file (Catch 22)
            var logger = new ConsoleEventLogger(LogLevel.Normal);

            var context = new RequestContext(this.TeamProjectCollectionUrl, this.TeamProjectName);
            var runtime = RuntimeContext.GetContext(
                () => this.PolicyFile,
                context,
                logger,
                (collectionUri, toImpersonate, runtimeContext) =>
                new Core.Facade.WorkItemRepository(collectionUri, toImpersonate, runtimeContext));

            if (!string.IsNullOrWhiteSpace(this.LogLevelName))
            {
                // command line wins
                LogLevel logLevel = (LogLevel)Enum.Parse(typeof(LogLevel), this.LogLevelName, true);
                runtime.Logger.MinimumLogLevel = logLevel;
            }

            if (runtime.HasErrors)
            {
                return(3);
            }

            using (EventProcessor eventProcessor = new EventProcessor(runtime))
            {
                try
                {
                    var workItemIds = new Queue <int>();
                    workItemIds.Enqueue(this.WorkItemId);

                    ProcessingResult result = null;
                    while (workItemIds.Count > 0)
                    {
                        context.CurrentWorkItemId = workItemIds.Dequeue();
                        var notification = context.Notification;

                        logger.StartingProcessing(context, notification);
                        result = eventProcessor.ProcessEvent(context, notification);
                        logger.ProcessingCompleted(result);

                        foreach (var savedId in eventProcessor.SavedWorkItems)
                        {
                            workItemIds.Enqueue(savedId);
                        }
                    }

                    return(result.StatusCode);
                }
                catch (Exception e)
                {
                    logger.ProcessEventException(e);
                    return(1);
                }
            }
        }
Beispiel #16
0
 public GuildController(IOptions <ClientSettings> clientSettings)
 {
     this.clientSettings                = clientSettings;
     eventProcessor                     = new EventProcessor();
     eventCharacterProcessor            = new EventCharacterProcessor();
     eventCharacterWaitingListProcessor = new EventCharacterWaitingListProcessor();
 }
Beispiel #17
0
    public void Initialize()
    {
        m_HasBeenInitialized = true;

        m_EventProcessor = GetComponent <EventProcessor>();
        if (m_EventProcessor == null)
        {
            m_EventProcessor = gameObject.AddComponent <EventProcessor>();
        }

        GStreamerNativeMethods.GUBUnityDebugLogPFN log_handler = null;
        if (m_DebugOutput.m_Enabled)
        {
            log_handler = (int level, string message) => Debug.logger.Log((LogType)level, "GUB", message);
        }

        GStreamerNativeMethods.Ref(m_DebugOutput.m_GStreamerDebugString.Length == 0 ? null : m_DebugOutput.m_GStreamerDebugString, log_handler);

        m_instanceHandle = GCHandle.Alloc(this);
        m_Pipeline       = new GStreamerNativeMethods(name + GetInstanceID(), OnFinish, OnError, OnQos, (IntPtr)m_instanceHandle);

#if (UNITY_EDITOR || UNITY_STANDALONE) && OCULUS
        audioGUID = "{" + OVRManager.audioOutId + "}";
#endif
    }
Beispiel #18
0
        public void WorkItem_addNew_succeeds()
        {
            var logger   = new DebugEventLogger();
            var settings = TestHelpers.LoadConfigFromResourceFile("NewObjects.policies", logger);

            var repository = new WorkItemRepositoryMock();

            var parent = new WorkItemMock(repository);

            parent.Id       = 1;
            parent.TypeName = "Bug";
            parent["Title"] = "My bug #1";

            repository.SetWorkItems(new[] { parent });

            var context = Substitute.For <IRequestContext>();
            var runtime = RuntimeContext.MakeRuntimeContext("settingsPath", settings, context, logger);

            using (var processor = new EventProcessor(repository, runtime))
            {
                var notification = Substitute.For <INotification>();
                notification.WorkItemId.Returns(1);

                var result = processor.ProcessEvent(context, notification);

                Assert.AreEqual(0, result.ExceptionProperties.Count());
                Assert.AreEqual(1, repository.LoadedWorkItems.Count);
                Assert.AreEqual(1, repository.CreatedWorkItems.Count);
                Assert.IsTrue(parent.InternalWasSaveCalled);
                Assert.IsTrue(parent.HasChildren());
            }
        }
Beispiel #19
0
 public void Initialize(IEnumerable <Event> events)
 {
     store            = new InMemoryEventStore(events);
     repository       = new InMemoryRepository();
     eventProcessor   = new EventProcessor(store, repository);
     commandProcessor = new CommandProcessor(repository, eventProcessor);
 }
Beispiel #20
0
        public LocalGameWebSocket(GameManager gameManager)
        {
            this._gameManager = gameManager;

            this._eventProcessor = new EventProcessor();
            this._eventProcessor.RegisterHandler(new Events.EventHandler <LocalGameStateMessage>(this.OnGameStateMessage));
        }
Beispiel #21
0
        /// <summary>
        /// Constructs a default window manager that holds the device (owner) in shared mode.
        /// </summary>
        public DefaultWindowManager(GraphicsDevice device, RenderTargetView renderTarget,
                                    Input.InputService input, IGuiTheme theme)
        {
            // Rendering data.
            this.device       = device;
            this.renderTarget = renderTarget;

            // Input data.
            this.processor = new EventProcessor(new EventPump(input.CreateDevice(InputDeviceType.Mouse),
                                                              input.CreateDevice(InputDeviceType.Keyboard)));

            // We bind events.
            this.processor.KeyDown         += KeyDown;
            this.processor.KeyUp           += KeyUp;
            this.processor.MouseButtonDown += MouseButtonDown;
            this.processor.MouseButtonUp   += MouseButtonUp;
            this.processor.MouseAxis       += MouseAxis;

            // We create "desktop manager".
            this.desktopManager = new GuiManager(new GraphicsCanvas(device, renderTarget, new Vector2f(1.0f, 1.0f)));
            this.pointer        = new SharpMedia.Graphics.GUI.Standalone.GuiPointer(desktopManager, processor,
                                                                                    null, null, new SharpMedia.Graphics.GUI.Standalone.Sensitivity());

            theme.AutomaticApply(this.pointer, false);

            // FIXME: add pointer somehow to be "forward"
            this.desktopManager.AddNLObject(pointer);

            // We create composition.
            this.compositor = new Compositor(device);
        }
Beispiel #22
0
        public void Should_aggregate_a_numeric_field()
        {
            var logger              = Substitute.For <ILogEvents>();
            var settings            = TestHelpers.LoadConfigFromResourceFile("SumFieldsOnSingleWorkItem.policies", logger);
            var alternateRepository = this.SetupFakeRepository();

            System.Func <IRuntimeContext, IScriptLibrary> scriptLibraryBuilder = (x) => Substitute.For <IScriptLibrary>();
            var context = Substitute.For <IRequestContext>();

            context.GetProjectCollectionUri().Returns(
                new System.Uri("http://*****:*****@"C:\Should_aggregate_a_numeric_field", settings, context, logger, (c) => alternateRepository, scriptLibraryBuilder);

            using (var processor = new EventProcessor(runtime))
            {
                var notification = Substitute.For <INotification>();
                notification.WorkItemId.Returns(1);

                var result = processor.ProcessEvent(context, notification);

                Assert.AreEqual(0, result.ExceptionProperties.Count);
                this.workItem.Received().Save();
                Assert.AreEqual(3.0D, this.workItem.Fields["Estimated Work"].Value);
                Assert.AreEqual(EventNotificationStatus.ActionPermitted, result.NotificationStatus);
            }
        }
Beispiel #23
0
        public void SetUp()
        {
            store = new Mock<AppendOnlyCollection<Event>>();
              repository = new Mock<Repository>();

              sut = new EventProcessor(store.Object, repository.Object);
        }
Beispiel #24
0
        public void RecordTracking(EventProcessor <ShippingEvent> eProc)
        {
            // Create event depending on TrackingType
            Port          OldLocation = TrackedShip.Location;
            ShippingEvent ev;

            if (TrackingType == TrackingType.Arrival)
            {
                ev = new ArrivalEvent(DateTime.Now, SetPort, TrackedShip, TrackingType);
            }
            else
            {
                ev = new DepartureEvent(DateTime.Now, SetPort, TrackedShip, TrackingType);
            }

            // send the event to the event handler (ship) which will update it's status on the provided event data
            eProc.ProcessEvent(ev);

            // notify the UI Tracking List so it can update itself
            ShipTrackedEventArgs args = new ShipTrackedEventArgs()
            {
                TrackingServiceId = TrackingServiceId,
                Recorded          = Recorded,
                TrackingType      = TrackingType,
                TrackedShip       = TrackedShip,
                OldLocation       = OldLocation,
                NewLocation       = SetPort,
            };

            // notify subscribers ...
            OnShipTracked(args);
        }
Beispiel #25
0
        public void GlobalList_UserParameterReplaceExisting_Succeeded()
        {
            var logger   = new DebugEventLogger();
            var settings = TestHelpers.LoadConfigFromResourceFile("UserParameters.policies", logger);

            var repository = new WorkItemRepositoryMock();

            var context = Substitute.For <IRequestContext>();

            context.GetProjectCollectionUri().Returns(
                new System.Uri("http://*****:*****@"C:\GlobalList_UserParameterReplaceExisting_Succeeded", settings, context, logger, (c, i, l) => repository);

            var workItem = new WorkItemMock(repository, runtime);

            workItem.Id       = 1;
            workItem.TypeName = "Use Case";
            workItem["Title"] = "The car shall have a maximum speed of {myParameter}(25) mph.";

            repository.SetWorkItems(new[] { workItem });

            using (var processor = new EventProcessor(runtime))
            {
                var notification = Substitute.For <INotification>();
                notification.WorkItemId.Returns(1);

                var result = processor.ProcessEvent(context, notification);

                Assert.AreEqual(0, result.ExceptionProperties.Count);
                Assert.IsTrue(workItem.InternalWasSaveCalled);
                Assert.AreEqual("The car shall have a maximum speed of {myParameter}(30) mph.", workItem.Fields["Title"].Value);
                Assert.AreEqual(EventNotificationStatus.ActionPermitted, result.NotificationStatus);
            }
        }
Beispiel #26
0
        // This is where the magic happens - returns one result per result target framework
        private AnalyzerResults BuildTargets(BuildEnvironment buildEnvironment, string targetFramework, string[] targetsToBuild, AnalyzerResults results)
        {
            using (CancellationTokenSource cancellation = new CancellationTokenSource())
            {
                using (AnonymousPipeLoggerServer pipeLogger = new AnonymousPipeLoggerServer(cancellation.Token))
                {
                    using (EventProcessor eventProcessor = new EventProcessor(Manager, this, BuildLoggers, pipeLogger, results != null))
                    {
                        // Run MSBuild
                        int    exitCode;
                        string fileName = GetCommand(buildEnvironment, targetFramework, targetsToBuild, pipeLogger.GetClientHandle(), out string arguments);
                        using (ProcessRunner processRunner = new ProcessRunner(fileName, arguments, Path.GetDirectoryName(ProjectFile.Path), GetEffectiveEnvironmentVariables(buildEnvironment), Manager.LoggerFactory))
                        {
                            processRunner.Exited = () => cancellation.Cancel();
                            processRunner.Start();
                            pipeLogger.ReadAll();
                            processRunner.Process.WaitForExit();
                            exitCode = processRunner.Process.ExitCode;
                        }

                        // Collect the results
                        results?.Add(eventProcessor.Results, exitCode == 0 && eventProcessor.OverallSuccess);
                    }
                }
            }
            return(results);
        }
Beispiel #27
0
        public void Should_be_able_to_get_round_robin_projections()
        {
            var processor = new EventProcessor(new Mock <IEventStoreConfiguration>().Object,
                                               new Mock <IPipelineFactory>().Object, new Mock <IProjectionRepository>().Object);

            processor.AddProjection(new Projection("projection-1", 1, Environment.MachineName,
                                                   AppDomain.CurrentDomain.BaseDirectory));
            processor.AddProjection(new Projection("projection-2", 1, Environment.MachineName,
                                                   AppDomain.CurrentDomain.BaseDirectory));

            var projection1 = processor.GetProjection();

            Assert.That(projection1, Is.Not.Null);

            var projection2 = processor.GetProjection();

            Assert.That(projection2, Is.Not.Null);

            Assert.That(processor.GetProjection(), Is.Null);

            processor.ReleaseProjection(projection1);

            Assert.That(processor.GetProjection(), Is.Not.Null);
            Assert.That(processor.GetProjection(), Is.Null);

            processor.ReleaseProjection(projection2);

            Assert.That(processor.GetProjection(), Is.Not.Null);
            Assert.That(processor.GetProjection(), Is.Null);

            Assert.That(() => processor.ReleaseProjection(new Projection("fail", 1, "machine", "folder")), Throws.TypeOf <InvalidOperationException>());
        }
Beispiel #28
0
        public async Task ShouldPublishToPoisonQueueWhenHandlerThrows()
        {
            var context = MockPartitionContext.CreateWithNoopCheckpoint("1");

            var attemptedToResolveHandler = false;

            var events = new[] { new EventData() };

            var resolver = new MockMessageHandlerResolver(
                async(body, headers) =>
            {
                attemptedToResolveHandler = true;
                await Task.Yield();
                throw new Exception("This message was bad.");
            });

            var poisonHandler = (MockPoisonMessageHandler)DependencyResolverFactory
                                .GetResolver()
                                .GetService(typeof(IPoisonMessageHandler));

            var processor = new EventProcessor(resolver, new MockCircuitBreaker(), 1, "test", Mock.Of <IDispatcherInstrumentationPublisher>());

            await processor.ProcessEventsAsync(context, events);

            Assert.True(attemptedToResolveHandler);
            Assert.True(
                poisonHandler.Messages.Any(),
                String.Format("Expected poison handler to have messages; count = {0}",
                              poisonHandler.Messages.Count()));
        }
Beispiel #29
0
        /// <summary>
        /// Optimizely constructor for managing Full Stack .NET projects.
        /// </summary>
        /// <param name="datafile">string JSON string representing the project</param>
        /// <param name="eventDispatcher">EventDispatcherInterface</param>
        /// <param name="logger">LoggerInterface</param>
        /// <param name="errorHandler">ErrorHandlerInterface</param>
        /// <param name="skipJsonValidation">boolean representing whether JSON schema validation needs to be performed</param>
        /// <param name="eventProcessor">EventProcessor</param>
        public Optimizely(string datafile,
                          IEventDispatcher eventDispatcher = null,
                          ILogger logger                        = null,
                          IErrorHandler errorHandler            = null,
                          UserProfileService userProfileService = null,
                          bool skipJsonValidation               = false,
                          EventProcessor eventProcessor         = null)
        {
            try {
                InitializeComponents(eventDispatcher, logger, errorHandler, userProfileService, null, eventProcessor);

                if (ValidateInputs(datafile, skipJsonValidation))
                {
                    var config = DatafileProjectConfig.Create(datafile, Logger, ErrorHandler);
                    ProjectConfigManager = new FallbackProjectConfigManager(config);
                }
                else
                {
                    Logger.Log(LogLevel.ERROR, "Provided 'datafile' has invalid schema.");
                }
            } catch (Exception ex) {
                string error = String.Empty;
                if (ex.GetType() == typeof(ConfigParseException))
                {
                    error = ex.Message;
                }
                else
                {
                    error = "Provided 'datafile' is in an invalid format. " + ex.Message;
                }

                Logger.Log(LogLevel.ERROR, error);
                ErrorHandler.HandleError(ex);
            }
        }
Beispiel #30
0
        public async Task ShouldNotPublishToPoisonQueueWhenMessageIsHandled()
        {
            var handled = false;

            var context = MockPartitionContext.CreateWithNoopCheckpoint("1");

            var events = new[] { new EventData() };

            var resovler = new MockMessageHandlerResolver(
                (body, headers) =>
            {
                handled = true;
                return(Task.FromResult <object>(null));
            });

            var poisonHandler = (MockPoisonMessageHandler)DependencyResolverFactory
                                .GetResolver()
                                .GetService(typeof(IPoisonMessageHandler));

            var processor = new EventProcessor(resovler, new MockCircuitBreaker(), 1, "test", Mock.Of <IDispatcherInstrumentationPublisher>());

            await processor.ProcessEventsAsync(context, events);

            Assert.True(handled);
            Assert.False(
                poisonHandler.Messages.Any(),
                String.Format("Expected poison handler to have no messages; count = {0}",
                              poisonHandler.Messages.Count()));
        }
        public void Should_be_able_to_get_round_robin_projections()
        {
            var processor = new EventProcessor(new Mock <IEventStoreConfiguration>().Object,
                                               new Mock <IPipelineFactory>().Object);

            processor.AddProjection(new Projection("projection-1", 1, Environment.MachineName, AppDomain.CurrentDomain.BaseDirectory));
            processor.AddProjection(new Projection("projection-2", 1, Environment.MachineName, AppDomain.CurrentDomain.BaseDirectory));

            var projection1 = processor.GetProjection();

            Assert.That(projection1, Is.Not.Null);

            var projection2 = processor.GetProjection();

            Assert.That(projection2, Is.Not.Null);

            Assert.That(processor.GetProjection(), Is.Null);

            processor.ReleaseProjection(projection1.Name);

            Assert.That(processor.GetProjection(), Is.Not.Null);
            Assert.That(processor.GetProjection(), Is.Null);

            processor.ReleaseProjection(projection2.Name);

            Assert.That(processor.GetProjection(), Is.Not.Null);
            Assert.That(processor.GetProjection(), Is.Null);

            processor.ReleaseProjection("does-not-exist");

            Assert.That(processor.GetProjection(), Is.Null);
        }
Beispiel #32
0
        public async Task ShouldProcessMessagesConcurrently()
        {
            const int Concurrency  = 4;
            const int MessageCount = 4;
            const int MsPerMessage = 300;

            var context = MockPartitionContext.CreateWithNoopCheckpoint("1");

            var events = Enumerable
                         .Range(0, MessageCount)
                         .Select(id => new EventData())
                         .ToArray();

            var resovler = new MockMessageHandlerResolver(
                async(body, headers) => { await Task.Delay(TimeSpan.FromMilliseconds(MsPerMessage)); });

            var processor = new EventProcessor(resovler, new MockCircuitBreaker(), Concurrency, "test", Mock.Of <IDispatcherInstrumentationPublisher>());

            var sw = Stopwatch.StartNew();
            await processor.ProcessEventsAsync(context, events);

            sw.Stop();

            Assert.True(sw.Elapsed < TimeSpan.FromMilliseconds(MsPerMessage * MessageCount));
            Assert.True(sw.Elapsed >= TimeSpan.FromMilliseconds(MsPerMessage));
        }
Beispiel #33
0
        public async Task BackgroundProcessinLogToleratesAnOwnershipClaimFailureWhenThePartitionIsOwned()
        {
            using var cancellationSource = new CancellationTokenSource();
            cancellationSource.CancelAfter(TimeSpan.FromSeconds(15));

            var partitionId       = "27";
            var partitionIds      = new[] { "0", partitionId };
            var wrappedExcepton   = new NotImplementedException("BOOM!");
            var expectedException = new EventHubsException(false, "eh", "LB FAIL", EventHubsException.FailureReason.GeneralError, wrappedExcepton);
            var completionSource  = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);
            var mockLogger        = new Mock <EventHubsEventSource>();
            var mockLoadBalancer  = new Mock <PartitionLoadBalancer>();
            var mockConnection    = new Mock <EventHubConnection>();
            var mockProcessor     = new Mock <EventProcessor <EventProcessorPartition> >(65, "consumerGroup", "namespace", "eventHub", Mock.Of <TokenCredential>(), default(EventProcessorOptions), mockLoadBalancer.Object)
            {
                CallBase = true
            };

            mockLoadBalancer
            .Setup(lb => lb.RunLoadBalancingAsync(partitionIds, It.IsAny <CancellationToken>()))
            .Callback(() =>
            {
                GetActivePartitionProcessors(mockProcessor.Object).TryAdd(
                    partitionId,
                    new EventProcessor <EventProcessorPartition> .PartitionProcessor(Task.CompletedTask, new EventProcessorPartition {
                    PartitionId = partitionId
                }, () => default, new CancellationTokenSource())
        public DebugProtocolService(JavaVM virtualMachine)
        {
            Contract.Requires<ArgumentNullException>(virtualMachine != null, "virtualMachine");

            _virtualMachine = virtualMachine;
            _eventProcessor = new EventProcessor(this);

            JniErrorHandler.ThrowOnFailure(_virtualMachine.GetEnvironment(out _environment));

            jvmtiCapabilities previousCapabilities;
            JvmtiErrorHandler.ThrowOnFailure(_environment.GetCapabilities(out previousCapabilities));

            var capabilities =
                new jvmtiCapabilities(
                    jvmtiCapabilities.CapabilityFlags1.CanTagObjects
                    | jvmtiCapabilities.CapabilityFlags1.CanGetSyntheticAttribute
                    | jvmtiCapabilities.CapabilityFlags1.CanGetSourceFileName
                    | jvmtiCapabilities.CapabilityFlags1.CanGetLineNumbers
                    | jvmtiCapabilities.CapabilityFlags1.CanGetSourceDebugExtension
                    | jvmtiCapabilities.CapabilityFlags1.CanAccessLocalVariables
                    | jvmtiCapabilities.CapabilityFlags1.CanGenerateSingleStepEvents
                    | jvmtiCapabilities.CapabilityFlags1.CanGenerateExceptionEvents
                    | jvmtiCapabilities.CapabilityFlags1.CanGenerateBreakpointEvents
                    | jvmtiCapabilities.CapabilityFlags1.CanGetBytecodes
                    | jvmtiCapabilities.CapabilityFlags1.CanSuspend
                    );
            JvmtiErrorHandler.ThrowOnFailure(RawInterface.AddCapabilities(_environment, ref capabilities));
        }
 public Task Execute(Uri recentFeedUri, EventProcessor eventProcessor, HttpResourceClient httpResourceClient, ClientState clientState)
 {
     foreach (var item in ((IEnumerable<SyndicationItem>)encounteredItems).Reverse())
     {
         eventProcessor.Process(item);
         clientState.RecordSuccessfullyProcessed(item);
     }
     return new Terminate();
 }
        public Task Execute(Uri recentFeedUri, EventProcessor eventProcessor, HttpResourceClient httpResourceClient, ClientState clientState)
        {
            var entry = feed.Items.ElementAt(entryIndex);

            if (!clientState.HaveAlreadyProcessed(entry))
            {
                encounteredItems.Add(entry);

                if (feed.Items.Count() > entryIndex + 1)
                {
                    return new NavigateEntryTask(feed, entryIndex + 1, encounteredItems);
                }
                return new NavigatePreviousArchiveTask(feed, encounteredItems);
            }

            return new ProcessItemsTask(encounteredItems);
        }
		public void Should_be_able_to_create_projections()
		{
			var serviceMock = new Mock<IProjectionService>();
			var processor = new EventProcessor(new EventProcessorConfiguration
			{
				ProjectionService = serviceMock.Object,
			});
			var eventProjection = new EventProjection("Test");
			var handler = new FakeEventHandler();

			serviceMock.Setup(m => m.GetEvent(0)).Returns(FakeEvent(new FakeEvent1 {PropertyOne = "value0"}, 0));
			serviceMock.Setup(m => m.GetEvent(1)).Returns(FakeEvent(new FakeEvent1 {PropertyOne = "value1"}, 1));
			serviceMock.Setup(m => m.GetEvent(2)).Returns(FakeEvent(new FakeEvent2 {PropertyTwo = "value2"}, 2));
			serviceMock.Setup(m => m.GetEvent(3)).Returns(FakeEvent(new FakeEvent1 {PropertyOne = "value3"}, 3));
			serviceMock.Setup(m => m.GetEvent(4)).Returns(FakeEvent(new FakeEvent2 {PropertyTwo = "value4"}, 4));
			serviceMock.Setup(m => m.GetEvent(5)).Returns(FakeEvent(new FakeEvent1 {PropertyOne = "[done]"}, 5));
			serviceMock.Setup(m => m.GetEvent(6)).Returns((ProjectionEvent) null);

			var position = new Queue<int>();

			for (var i = 0; i < 6; i++)
			{
				position.Enqueue(i);
			}

			serviceMock.Setup(m => m.GetSequenceNumber("Test")).Returns(() => position.Count > 0 ? position.Dequeue() : 6);

			eventProjection.AddEventHandler(handler);

			processor.AddEventProjection(eventProjection);

			processor.Start();

			while (!handler.HasValue("[done]"))
			{
				Thread.Sleep(250);
			}

			processor.Stop();
		}
 public Task Execute(Uri recentFeedUri, EventProcessor eventProcessor, HttpResourceClient httpResourceClient, ClientState clientState)
 {
     return new NavigateEntryTask(new Feed(recentFeedUri, httpResourceClient), 0, new List<SyndicationItem>());
 }
 public CaptureUserInstructionsPresenter(CaptureUserInstructionsView view, EventProcessor pump)
 {
     this.view = view;
     this.pump = pump;
 }
            public override bool ProcessEvent(JvmtiEnvironment environment, JniEnvironment nativeEnvironment, EventProcessor processor, ThreadId thread, TaggedReferenceTypeId @class, Location? location)
            {
                if (!location.HasValue)
                    return false;

                return _location.Index == location.Value.Index
                    && _location.Class == location.Value.Class
                    && _location.Method == location.Value.Method;
            }
 public override bool ProcessEvent(JvmtiEnvironment environment, JniEnvironment nativeEnvironment, EventProcessor processor, ThreadId thread, TaggedReferenceTypeId @class, Location? location)
 {
     return true;
 }
            public override bool ProcessEvent(JvmtiEnvironment environment, JniEnvironment nativeEnvironment, EventProcessor processor, ThreadId thread, TaggedReferenceTypeId @class, Location? location)
            {
                if (!base.ProcessEvent(environment, nativeEnvironment, processor, thread, @class, location))
                    return false;

                // Step Out is implemented with Frame Pop events set at the correct depth
                if (_depth == StepDepth.Out)
                {
                    if (location.HasValue && !location.Value.Method.Equals(_lastMethod))
                    {
                        _lastLocation = new jlocation((long)location.Value.Index);
                        _lastMethod = location.Value.Method;
                        UpdateLastLine(environment);
                    }

                    return true;
                }

                using (var threadHandle = environment.VirtualMachine.GetLocalReferenceForThread(nativeEnvironment, thread))
                {
                    int stackDepth;
                    JvmtiErrorHandler.ThrowOnFailure(environment.GetFrameCount(threadHandle.Value, out stackDepth));

                    if (_hasMethodInfo && stackDepth > _stackDepth)
                    {
                        bool convertToFramePop;
                        if (location.HasValue && (!_convertedToFramePop || !_framePopMethod.Equals(location.Value.Method)) && ShouldSkipCurrentMethod(processor.VirtualMachine, environment, nativeEnvironment, threadHandle.Value, stackDepth, location.Value, out convertToFramePop))
                        {
                            if (convertToFramePop)
                            {
                                // remove the single step event
                                JvmtiErrorHandler.ThrowOnFailure((jvmtiError)processor.ClearEventInternal(EventKind.FramePop, this.RequestId));
                                JvmtiErrorHandler.ThrowOnFailure((jvmtiError)processor.ClearEventInternal(EventKind.SingleStep, this.RequestId));
                                // set an actual step filter to respond when the thread arrives back in this frame
                                JvmtiErrorHandler.ThrowOnFailure((jvmtiError)processor.SetEventInternal(environment, nativeEnvironment, EventKind.FramePop, this));
                                _convertedToFramePop = true;
                                _framePopMethod = location.Value.Method;
                            }

                            return false;
                        }
                        else
                        {
                            _convertedToFramePop = false;
                            return true;
                        }
                    }
                    else if (stackDepth == _stackDepth)
                    {
                        if (_size == StepSize.Statement && _disassembledMethod != null)
                        {
                            int instructionIndex = _disassembledMethod.Instructions.FindIndex(i => (uint)i.Offset == location.Value.Index);
                            if (instructionIndex >= 0 && _evaluationStackDepths != null && (_evaluationStackDepths[instructionIndex] ?? 0) != 0)
                            {
                                return false;
                            }
                            else if (instructionIndex >= 0 && _disassembledMethod.Instructions[instructionIndex].OpCode.FlowControl == JavaFlowControl.Branch)
                            {
                                // follow branch instructions before stopping
                                return false;
                            }
                        }
                        else if (_lastLine != null)
                        {
                            // see if we're on the same line
                            LineNumberData[] lines;
                            jvmtiError error = environment.GetLineNumberTable(location.Value.Method, out lines);
                            if (error == jvmtiError.None)
                            {
                                LineNumberData entry = lines.LastOrDefault(i => i.LineCodeIndex <= (long)location.Value.Index);
                                if (entry.LineNumber == _lastLine)
                                    return false;
                            }
                        }
                    }

                    if (location.HasValue)
                    {
                        _lastLocation = new jlocation((long)location.Value.Index);
                        _lastMethod = location.Value.Method;
                        UpdateLastLine(environment);
                    }

                    _stackDepth = stackDepth;
                    return true;
                }
            }
 public abstract bool ProcessEvent(JvmtiEnvironment environment, JniEnvironment nativeEnvironment, EventProcessor processor, ThreadId thread, TaggedReferenceTypeId @class, Location? location);
Beispiel #44
0
 public Task Execute(Uri recentFeedUri, EventProcessor eventProcessor, HttpResourceClient httpResourceClient, ClientState clientState)
 {
     throw new InvalidOperationException("Should not be executing the terminal state.");
 }
            public override bool ProcessEvent(JvmtiEnvironment environment, JniEnvironment nativeEnvironment, EventProcessor processor, ThreadId thread, TaggedReferenceTypeId @class, Location? location)
            {
                _current++;
                if (_current == _count)
                {
                    _current = 0;
                    return true;
                }

                return false;
            }
 protected UsingEventProcessorBase()
 {
     TransientErrorRegistry.Setup(mock => mock.IsTransient(It.IsAny<ConcurrencyException>())).Returns(true);
     Processor = new EventProcessor(HandlerRegistry.Object, TransientErrorRegistry.Object, new EventProcessorSettings());
 }
            public override bool ProcessEvent(JvmtiEnvironment environment, JniEnvironment nativeEnvironment, EventProcessor processor, ThreadId thread, TaggedReferenceTypeId @class, Location? location)
            {
                foreach (EventFilter filter in _filters)
                {
                    if (!filter.ProcessEvent(environment, nativeEnvironment, processor, thread, @class, location))
                        return false;
                }

                return true;
            }
Beispiel #48
0
 public Client(string recentFeedUri, EventProcessor eventProcessor, HttpResourceClient httpResourceClient)
 {
     this.eventProcessor = eventProcessor;
     this.httpResourceClient = httpResourceClient;
     this.recentFeedUri = new Uri(recentFeedUri);
 }
 public Task Execute(Uri recentFeedUri, EventProcessor eventProcessor, HttpResourceClient httpResourceClient, ClientState clientState)
 {
     if (feed.HasPreviousArchive)
         return new NavigateEntryTask(feed.PreviousArchive, 0, encounteredItems);
     return new ProcessItemsTask(encounteredItems);
 }