Example #1
0
        public void EventPumpQueueLength(int numberOfProducers, bool producerDelay)
        {
            EventQueue q = new EventQueue();
            EventProducer[] producers = new EventProducer[numberOfProducers];
            for (int i = 0; i < numberOfProducers; i++)
            {
                producers[i] = new EventProducer(q, i, producerDelay);
            }

            using (EventPump pump = new EventPump(NullListener.NULL, q, false))
            {
                pump.Name = "EventPumpQueueLength";
                pump.Start();

                foreach (EventProducer p in producers)
                {
                    p.ProducerThread.Start();
                }
                foreach (EventProducer p in producers)
                {
                    p.ProducerThread.Join();
                }
                pump.Stop();
            }
            Assert.That(q.Count, Is.EqualTo(0));

            foreach (EventProducer p in producers)
            {
                Console.WriteLine(
                    "#Events: {0}, MaxQueueLength: {1}", p.SentEventsCount, p.MaxQueueLength);
                Assert.IsNull(p.Exception, "{0}", p.Exception);
            }
        }
Example #2
0
 public EventList(EventQueue<string> events)
 {
     InitializeComponent();
     EventQueue = events;
     EventQueue.Updated += Events_Updated;
     ReloadEvents();
 }
Example #3
0
        /// <summary>
        /// Constructs a new EventManager.
        /// </summary>
        /// <param name="robotProxy">the robot proxy that this event manager applies to.</param>
        public EventManager(BasicRobotProxy robotProxy)
        {
            this.robotProxy = robotProxy;
            eventQueue = new EventQueue();

            RegisterEventNames();
            Reset();
        }
Example #4
0
        /**
	     * EventManager constructor comment.
	     *
	     * @param robotProxy robotProxy
	     */

        public EventManager(BasicRobotProxy robotProxy)
        {
            registerNamedEvents();
            this.robotProxy = robotProxy;
            eventQueue = new EventQueue();

            reset();
        }
Example #5
0
 /// <summary>
 /// start a small server that listens to UDP messages through _port 1337(as indicated when initializing the server instance).
 /// </summary>
 /// <param name="_port"></param>
 public Server(int _port)
 {
     this._iPort = _port;
     _lMessageBacklog = new EventQueue<NetworkMessage>();
     _lPlayerRooms = new EventList<Hub>();
     Instance = this;
     Console.WriteLine("Setting up the server...");
     MessageReceived += ParseMessage;
 }
Example #6
0
 public Environment(DateTime initialDateTime, int randomSeed, TimeSpan? defaultStep = null) {
   DefaultTimeStepSeconds = (defaultStep ?? TimeSpan.FromSeconds(1)).Duration().TotalSeconds;
   StartDate = initialDateTime;
   Now = initialDateTime;
   Random = new SystemRandom(randomSeed);
   ScheduleQ = new EventQueue(InitialMaxEvents);
   Queue = new Queue<Event>();
   Logger = Console.Out;
 }
 /// <summary>
 /// Default constructor
 /// </summary>
 public EventOptions()
 {
     HostName = _hostName;
     OnErrorHttpCaptureFlags = HttpCaptureFlags.All;
     SourceLevels = SourceLevels.All;
     ConfigKeys = new Keys();
     ConnectorType = "HashTag.Logging.Client.NLog.NLogEventConnector, HashTag.Logging.Client";
     _queue = new EventQueue(this);
 }
 private static void VerifyQueue(EventQueue q)
 {
     for (int index = 0; index < events.Length; index++)
     {
         Event e = q.Dequeue(false);
         Assert.AreEqual(events[index].GetType(), e.GetType(),
             string.Format("Event {0}", index));
     }
 }
Example #9
0
 public void Log(GroupEvent e)
 {
     if (this.queue == null)
     {
         this.queue = new EventQueue(EventQueueId.Service, EventQueueType.Master, EventQueuePriority.Normal, 100000, null);
         this.queue.Enqueue(new OnQueueOpened(this.queue));
         this.framework.EventBus.CommandPipe.Add(this.queue);
     }
     this.queue.Enqueue(e);
 }
Example #10
0
 public void Attach(EventBus bus)
 {
     var q = new EventQueue(EventQueueId.Data, EventQueueType.Master, EventQueuePriority.Normal, 25600, null)
     {
         IsSynched = true,
         Name = $"attached {bus.framework.Name}"
     };
     q.Enqueue(new OnQueueOpened(q));
     bus.DataPipe.Add(q);
     this.attached[this.attachedCount++] = q;
 }
Example #11
0
 public void PumpAutoStopsOnRunFinished()
 {
     EventQueue q = new EventQueue();
     EventPump pump = new EventPump( NullListener.NULL, q, true );
     Assert.IsFalse( pump.Pumping, "Should not be pumping initially" );
     StartPump( pump, 1000 );
     Assert.IsTrue( pump.Pumping, "Pump failed to start" );
     q.Enqueue( new RunFinishedEvent( new Exception() ) );
     WaitForPumpToStop( pump, 1000 );
     Assert.IsFalse( pump.Pumping, "Pump failed to stop" );
 }
 public void SetUp()
 {
     theQueue = new EventQueue<FakeTopic>();
     theQueue.Write(new ServerEvent("2", "2"));
     theQueue.Write(new ServerEvent("1", "1"));
     
     for (int i = 3; i < 8; i++)
     {
         theQueue.Write(new ServerEvent(i.ToString(), i.ToString()));
     }    
 }
Example #13
0
 public void PumpEvents()
 {
     EventQueue q = new EventQueue();
     EnqueueEvents( q );
     QueuingEventListener el = new QueuingEventListener();
     EventPump pump = new EventPump( el, q, false );
     Assert.IsFalse( pump.Pumping, "Should not be pumping initially" );
     StartPump( pump, 1000 );
     Assert.IsTrue( pump.Pumping, "Pump should still be running" );
     StopPump( pump, 1000 );
     Assert.IsFalse( pump.Pumping, "Pump should have stopped" );
     VerifyQueue( el.Events );
 }
Example #14
0
 protected override void OnConnected()
 {
     foreach (var s in Series)
     {
         var q = new EventQueue(EventQueueId.Data, EventQueueType.Master, EventQueuePriority.Normal, 25600, null)
         {
             IsSynched = true,
             Name = s.Name
         };
         q.Enqueue(new OnQueueOpened(q));
         this.framework.EventBus.DataPipe.Add(q);
         this.emitters.Add(new DataSeriesObject(s, DateTime1, DateTime2, q, Processor));
     }
 }
        public void spin_up_pre_builds()
        {
            var factory = MockRepository.GenerateMock<IEventQueueFactory<FakeTopic>>();
            var queue = new EventQueue<FakeTopic>();
            var topic = new FakeTopic{
                Name = "Top"
            };

            factory.Stub(x => x.BuildFor(topic)).Return(queue);

            var family = new TopicFamily<FakeTopic>(factory);
            family.SpinUpChannel(topic);

            factory.AssertWasCalled(x => x.BuildFor(topic));
        }
Example #16
0
 public void PumpEventsWithAutoStop()
 {
     EventQueue q = new EventQueue();
     EnqueueEvents( q );
     QueuingEventListener el = new QueuingEventListener();
     EventPump pump = new EventPump( el, q, true );
     pump.Start();
     int tries = 10;
     while( --tries > 0 && q.Count > 0 )
     {
         Thread.Sleep(100);
     }
     VerifyQueue( el.Events );
     Assert.IsFalse( pump.Pumping, "Pump failed to stop" );
 }
Example #17
0
File: Base.cs Project: vokac/F2B
        public BaseInput(InputElement input, SelectorElement selector, EventQueue queue)
            : base()
        {
            InputName = input.Name;
            InputType = input.Type;
            SelectorName = selector.Name;
            Processor = selector.Processor;

            switch (selector.Login)
            {
                case "success": Login = LoginStatus.SUCCESS; break;
                case "failure": Login = LoginStatus.FAILURE; break;
                default: Login = LoginStatus.UNKNOWN; break;
            }

            equeue = queue;
        }
Example #18
0
File: Service.cs Project: vokac/F2B
        public void Produce(EventEntry item, string processor, EventQueue.Priority priority = EventQueue.Priority.Low)
        {
            if (equeue == null)
            {
                Log.Error("Unable to produce events before queue initialization!?!?");
                return;
            }

            if (string.IsNullOrEmpty(processor))
            {
                Log.Error("Unable to queue events with empty processor name");
                return;
            }

            Log.Info("Service[" + item.Id + "@" + item.Input.Name + "] (re)queued message"
                + " with first processor name " + processor);
            equeue.Produce(item, processor, priority);
        }
        public void Start(int port, CryptoAlgoId_Values cryptoAlgoId, byte[] content, EventQueue eventQueue)
        {
            this.cryptoAlgoId = cryptoAlgoId;
            this.content = content;
            this.eventQueue = eventQueue;
            this.aes = PccrrUtitlity.CreateAes(cryptoAlgoId);
            this.iv = new byte[16];
            for (int i = 0; i < iv.Length; i++)
            {
                this.iv[i] = (byte)i;
            }

            pccrrServer = new PccrrServer(port);

            pccrrServer.MessageArrived += new MessageArrivedEventArgs(pccrrServer_MessageArrived);

            pccrrServer.StartListening();
        }
Example #20
0
        public RuntimeEngine(RuntimeEntityService entityService, ISystemManager systemManager, EventQueue eventQueue, ILogger logger)
        {
            AddEntityAccessGate = new AccessGate();
            EventQueue = eventQueue;
            _logger = logger;
            EntityService = entityService;
            EntityService.AddEntityAccessGate = AddEntityAccessGate;
            SystemManager = systemManager;
            SystemUpdateScheduler = new SystemUpdateScheduler(SystemManager.Systems);

            foreach (var updateBurst in SystemUpdateScheduler.UpdateBursts)
            {
                _logger.Info($"Update Burst: {string.Join(", ", updateBurst.Systems.Select(p => p.System.Name))}");
            }

            // Add any entities that are already loaded into the engine.
            SystemManager.AddEntities(entityService.Entities);
        }
        protected bool Authenticate(Session session, Identity identity, Request request)
        {
            var correlationId = new CorrelationID();
            var eventQueue = new EventQueue();
            session.SendAuthorizationRequest(request, identity, eventQueue, correlationId);
            while (true)
            {
                var eventArgs = eventQueue.NextEvent();

                foreach (var message in eventArgs.GetMessages())
                {
                    if (MessageTypeNames.AuthorizationFailure.Equals(message.MessageType))
                        return false;

                    if (MessageTypeNames.AuthorizationSuccess.Equals(message.MessageType))
                        return true;

                    throw new Exception("Unknown message type: " + message);
                }
            }
        }
 private void CleanUpVoid(object _)
 {
     CleanUpOldEndPoints(TimeSpan.FromMilliseconds(config.SavedEndPointTtl));
     EventQueue.AddEvent(CleanUpVoid, null, DateTime.Now + TimeSpan.FromMilliseconds(config.SavedEndPointsCleanUpInterval));
 }
Example #23
0
        public ICollection <IGeometry> HandleEvent(CircleEvent sweepEvent, EventQueue eventQueue, BeachLine beachLine)
        {
            if (sweepEvent.Arc.Parent == null)
            {
                throw new InvalidOperationException($"CircleEvent: Arc {sweepEvent.Arc.Site}: Parent of node {0} is null");
            }

            var leftParent  = sweepEvent.Arc.GetParent(TraverseDirection.CounterClockwise);
            var rightParent = sweepEvent.Arc.GetParent(TraverseDirection.Clockwise);
            var left        = leftParent?.GetLeaf(TraverseDirection.CounterClockwise);
            var right       = rightParent?.GetLeaf(TraverseDirection.Clockwise);

            if (left == null || right == null)
            {
                throw new InvalidOperationException($"Neighbor of node {sweepEvent.Arc.Site} is null.");
            }

            if (left.CircleEvent != null)
            {
                eventQueue.Remove(left.CircleEvent);
                left.CircleEvent = null;
            }
            if (right.CircleEvent != null)
            {
                eventQueue.Remove(right.CircleEvent);
                right.CircleEvent = null;
            }

            var p = new Point(sweepEvent.Point.X, _calculationService.GetY(sweepEvent.Arc.Site, sweepEvent.Point));

            leftParent.HalfEdge.EndPoint  = p;
            rightParent.HalfEdge.EndPoint = p;

            var vertex = new Vertex {
                Point = p
            };

            ConnectHalfEdgeWithVertex(leftParent.HalfEdge, vertex, (e, v) => e.End  = v);
            ConnectHalfEdgeWithVertex(rightParent.HalfEdge, vertex, (e, v) => e.End = v);

            // Add third half edge
            var halfEdge = new HalfEdge(p, left.Site, right.Site);

            ConnectHalfEdgeWithVertex(halfEdge, vertex, (e, v) => e.Start = v);
            Logger.Instance.Log($"Left parent: {leftParent.HalfEdge}");
            Logger.Instance.Log($"Right parent: {rightParent.HalfEdge}");
            var higher = sweepEvent.Arc.GetFirstParent(leftParent, rightParent);

            Logger.Instance.Log($"Higher node: {higher}");
            Logger.Instance.Log($"Higher edge old: {higher.HalfEdge}");
            higher.HalfEdge = halfEdge;

            if (vertex.HalfEdges.Count != 3)
            {
                var message = $"Halfedge {halfEdge} is already connected to Vertex {vertex}";
                Logger.Instance.Log(message);
                Logger.Instance.ToFile();
                throw new InvalidOperationException(message);
            }

            Logger.Instance.Log($"CircleEvent: Remove Arc {sweepEvent.Arc.Site}");
            beachLine.RemoveLeaf(sweepEvent.Arc);

            var circleEvents = beachLine.GenerateCircleEvent(new[] { left, right }, sweepEvent.Point.Y);

            eventQueue.Insert(circleEvents);

            return(new List <IGeometry> {
                vertex, halfEdge
            });
        }
 public void Stop()
 {
     EventQueue.StopReading();
     EventQueue.Close();
 }
Example #25
0
 private DataSeriesObject CreateDataSeriesEmitter(DataSeries series, DateTime dateTime1, DateTime dateTime2)
 {
     var q = new EventQueue(EventQueueId.Data, EventQueueType.Master, EventQueuePriority.Normal, 25600, null)
     {
         IsSynched = true,
         Name = series.Name
     };
     q.Enqueue(new OnQueueOpened(q));
     this.framework.EventBus.DataPipe.Add(q);
     return new DataSeriesObject(series, dateTime1, dateTime2, q, Processor);
 }
Example #26
0
        /// <summary>
        /// Creates a new <see cref="ViewerPresentationLayout"/> instance and instantiates all of the child controls.
        /// </summary>
        /// <param name="model">The model whose <see cref="WorkspaceModel.CurrentDeckTraversal"/> property will
        /// be used to display the current slide and deck.</param>
        public ViewerPresentationLayout(PresenterModel model)
        {
            this.Name    = "ViewerPresentationLayout";
            this.m_Model = model;

            this.m_EventQueue = new ControlEventQueue(this);

            m_Model.Workspace.CurrentDeckTraversal.ListenAndInitialize(m_EventQueue, new Property <DeckTraversalModel> .EventHandler(this.HandleTraversalChanged));

            // Create the film strip, docked to the right side of the container.
            this.m_DeckStrip = new DeckStrip(this.m_Model);
            /// Filmstrip docking
            this.m_DeckStrip.Dock = DockStyle.Right;

            this.m_MainSlideViewer = new MainSlideViewer(this.m_Model, true);

            // Make the deck strip resizable with a LinkedSplitter.
            // The splitter automatically sets its dock to be the same as the FilmStrip and
            // keeps z-order correct with respect to the FilmStrip and the MainSlideViewer.
            this.m_DeckStripSplitter = new LinkedSplitter(this.m_DeckStrip, this.m_MainSlideViewer);

            // Create the MainSlideViewer, which occupies the remaining space in the container.
            this.m_MainSlideViewer.Dock = DockStyle.Fill;

            #region RealTimeStylus Initialization
            // Create a new RealTimeStylus, which will process ink drawn on the MainSlideViewer.
            this.m_RealTimeStylus = new RealTimeStylus(this.m_MainSlideViewer, true);

            try {
                // Enable touch input for the real time stylus
                this.m_RealTimeStylus.MultiTouchEnabled = true;
                this.m_TouchGestureHandler = new TouchGestureHandler(this.m_Model, this.m_EventQueue);
                this.m_RealTimeStylus.SyncPluginCollection.Add(this.m_TouchGestureHandler);
            }
            catch { }

            // Make sure the TransformableDynamicRenderer and InkAnnotationCollector
            // find out whenever the current StylusModel changes.
            this.m_StylusInputSelector = new StylusInputSelector(this.m_Model, this.m_RealTimeStylus);
            this.m_RealTimeStylus.SyncPluginCollection.Add(this.m_StylusInputSelector);

            // Scale the ink to the inverse of the MainSlideViewer's transform.
            // This keeps the ink's coordinates correct when the MainSlideViewer's transform
            // is applied again later by the TransformableDynamicRenderer and InkAnnotationCollector.
            this.m_InkTransformFilter = new InkTransformFilter(this.m_MainSlideViewer.SlideDisplay);
            this.m_RealTimeStylus.SyncPluginCollection.Add(this.m_InkTransformFilter);

            // Create a *synchronous* TransformableDynamicRenderer, which will render ink received directly
            // from the RealTimeStylus on a high-priority thread.
            this.m_TransformableDynamicRenderer         = new TransformableDynamicRendererLinkedToDisplay(this.m_MainSlideViewer, this.m_MainSlideViewer.SlideDisplay);
            this.m_TransformableDynamicRenderer.Enabled = true;
            this.m_RealTimeStylus.SyncPluginCollection.Add(this.m_TransformableDynamicRenderer);

            // Don't dynamically render ink on the main slide viewer twice.  The MainSlideViewer's RealTimeInkSheetRenderer's
            // own TransformableDynamicRenderer would render the ink on a low-priority asynchronous thread, which is
            // fine for secondary slide viewers and the FilmStrip, but not fine for the MainSlideViewer.
            using (Synchronizer.Lock(this.m_MainSlideViewer.SlideDisplay.SyncRoot)) {
                this.m_MainSlideViewer.SlideDisplay.RenderLocalRealTimeInk = false;
            }

            // Create an InkAnnotationCollector and wrap it in an InkSheetAdapter,
            // which sends ink from the RealTimeStylus to the RealTimeInkSheetModel
            // of the MainSlideViewer's current slide.
            this.m_InkAnnotationCollector = new InkAnnotationCollector();
            this.m_InkAnnotationCollector_InkSheetAdapter = new InkSheetAdapter(this.m_MainSlideViewer.SlideDisplay, this.m_InkAnnotationCollector);
            this.m_RealTimeStylus.AsyncPluginCollection.Add(this.m_InkAnnotationCollector);

            this.m_LassoPlugin = new LassoPlugin(this.m_MainSlideViewer, this.m_MainSlideViewer.SlideDisplay);
            this.m_LassoPlugin_InkSheetAdapter = new InkSheetAdapter(this.m_MainSlideViewer.SlideDisplay, this.m_LassoPlugin);
            this.m_RealTimeStylus.SyncPluginCollection.Add(this.m_LassoPlugin);

            this.m_EraserPlugin = new EraserPlugin(this.m_MainSlideViewer.SlideDisplay);
            this.m_EraserPlugin_InkSheetAdapter = new InkSheetAdapter(this.m_MainSlideViewer.SlideDisplay, this.m_EraserPlugin);
            this.m_RealTimeStylus.SyncPluginCollection.Add(this.m_EraserPlugin);

            // Now that all the plugins have been added, enable the RealTimeStylus.
            this.m_RealTimeStylus.Enabled = true;
            #endregion RealTimeStylus Initialization

            // Create a DeckTraversalModelAdapter, which causes the MainSlideViewer to always display the
            // current slide of the current deck of the PresenterModel's current DeckTraversalModel.
            this.m_WorkspaceModelAdapter = new WorkspaceModelAdapter(this.m_MainSlideViewer.SlideDisplay.EventQueue, this.m_MainSlideViewer, this.m_Model);

            // Create the Slide Preview control
            this.m_SlidePreview = new SlidePreview(this.m_Model, this.m_DeckStripSplitter);
            this.m_PreviewTraversalModelAdapter
                = new PreviewTraversalModelAdapter(this.m_SlidePreview.m_EventQueue, this.m_SlidePreview.m_PreviewSlideViewer, this.m_Model);

            // Create the Second Monitor Form, this displays the slide on the secondary display
            this.m_SecondMonitorForm = new SecondMonitorForm(this.m_Model);
            this.ParentChanged      += new EventHandler(OnParentChanged);

            // Create the Role Synchronizer for the MainSlideViewer
            this.m_RoleSync = new RoleSynchronizer(this.m_MainSlideViewer, this.m_Model.Participant);

            #region Add Controls
            // Add the SlidePreview Control
            this.Controls.Add(this.m_SlidePreview);

            // Now, add the controls in reverse order of their docking priority.
            // The MainSlideViewer gets added first so its Fill dock-style will be effective.
            this.Controls.Add(this.m_MainSlideViewer);

            // Next, dock the FilmStripSplitter and the FilmStrip in reverse order,
            // so that the FilmStripSplitter will be farther away from the edge of the container.
            this.Controls.Add(this.m_DeckStripSplitter);
            this.Controls.Add(this.m_DeckStrip);


            #endregion Add Controls
        }
Example #27
0
	// Use this for initialization
	void Start () {
		instance = this;
		actionEvents = new List<ActionEvent> ();
	}
Example #28
0
            public ExclusiveSynchronizationContext(SynchronizationContext old)
            {
                var oldEx = old as ExclusiveSynchronizationContext;

                _items = null != oldEx ? oldEx._items : new EventQueue();
            }
Example #29
0
        public override void Self_OnChat(object sender, ChatEventArgs e)
        {
            var type       = e.Type;
            var message    = e.Message;
            var id         = e.SourceID;
            var fromName   = e.FromName;
            var sourceType = e.SourceType;
            var position   = e.Position;
            var ownerid    = e.OwnerID;
            var audible    = e.AudibleLevel;


            PCode pCode = PCode.None;

            if (sourceType == ChatSourceType.Agent)
            {
                pCode = PCode.Avatar;
            }
            if (sourceType == ChatSourceType.Object)
            {
                pCode = PCode.Prim;
            }
            SimObject source = AsObject(fromName, id, pCode);
            object    s1     = source;

            if (source == null)
            {
                s1 = id;
            }
            if (!string.IsNullOrEmpty(fromName))
            {
                s1 = fromName;
            }
            if (source != null)
            {
                s1 = source;
            }
            object location = AsLocation(e.Simulator, position, source);

            if (ownerid != id)
            {
                SendNewRegionEvent(SimEventType.NETWORK, "Bug", "id!=ownerID?", "on-chat",
                                   message, audible, type, sourceType, fromName, id, ownerid, location);
            }

            if (type == ChatType.Normal || type == ChatType.Shout || type == ChatType.Whisper)
            {
                EventQueue.Enqueue(() =>
                                   SendNewRegionEvent(SimEventType.SOCIAL, "ChatType-" + type.ToString(),
                                                      ToParameter("senderOfInfo", s1),
                                                      ToParameter("infoTransferred-NLString", message),
                                                      audible,
                                                      type,
                                                      sourceType,
                                                      ToParameter("eventPrimarilyOccursAt", location)));
                return;
            }

            if (string.IsNullOrEmpty(message))
            {
                EventQueue.Enqueue(
                    () =>
                    SendNewRegionEvent(SimEventType.SOCIAL, "ChatType-" + type.ToString(),
                                       audible,
                                       sourceType,
                                       type,
                                       ToParameter("senderOfInfo", s1),
                                       ToParameter("eventPrimarilyOccursAt", location)));
                return;
            }
            EventQueue.Enqueue(() =>
                               SendNewRegionEvent(SimEventType.SOCIAL, "ChatType-" + type.ToString(),
                                                  ToParameter("senderOfInfo", s1),
                                                  ToParameter("infoTransferred-NLString", message),
                                                  audible,
                                                  type,
                                                  sourceType,
                                                  ToParameter("eventPrimarilyOccursAt", location)));
        }
Example #30
0
        public override void Self_OnInstantMessage(object sender, InstantMessageEventArgs e)
        {
            var im = e.IM;

            if (im.FromAgentID != UUID.Zero)
            {
                AddName2Key(im.FromAgentName, im.FromAgentID);
                if (im.RegionID != UUID.Zero)
                {
                    AvatarRegion[im.FromAgentID] = im.RegionID;
                    Debug("Avatar region " + im.FromAgentName + " " + im.RegionID);
                }
            }
            bool Conference = false;
            bool GroupIM    = im.GroupIM || client.Groups.GroupName2KeyCache.ContainsKey(im.IMSessionID);

            if (GroupIM)
            {
                DeclareGroup(im.IMSessionID);
            }
            if (im.Dialog == InstantMessageDialog.SessionSend)
            {
                if (!GroupIM)
                {
                    Conference = true;
                }
            }

            PCode  pcode = PCode.None;
            object s     = im.FromAgentName;

            if (string.IsNullOrEmpty(im.FromAgentName) || im.FromAgentName == "Object" || !im.FromAgentName.Contains(" "))
            {
                s     = im.FromAgentID;
                pcode = PCode.Prim;
            }
            else
            {
                pcode = PCode.Avatar;
            }
            InstantMessageDialog d = im.Dialog;

            if (d == InstantMessageDialog.StartTyping || d == InstantMessageDialog.StopTyping)
            {
                pcode = PCode.Avatar;
            }
            if (!Conference && GroupIM)
            {
                //"recipientOfInfo-Intended";
            }
            SimObject source = AsObject(im.FromAgentName, im.FromAgentID, pcode);

            if (source != null)
            {
                s = source;
            }
            object location = AsLocation(im.RegionID, im.Position);

            EventQueue.Enqueue(() =>
                               client.SendPersonalEvent(SimEventType.SOCIAL, "InstantMessageDialog-" + im.Dialog.ToString() + (GroupIM ? "-Group" : ""),
                                                        ToParameter("senderOfInfo", s),
                                                        ToParameter("infoTransferred-NLString", im.Message),
                                                        ToParameter("recipientOfInfo-Intended", im.ToAgentID),
                                                        im.Offline,
                                                        im.IMSessionID,
                                                        ToParameter("eventPrimarilyOccursAt", location),
                                                        //(im.GroupIM ? "GroupIM" : ""),
                                                        //im.Dialog,
                                                        im.ParentEstateID));
        }
Example #31
0
 private Interactor(Stream stream, string name, IPAddress address, DistributorRole distributorRole, EventQueue <InteractorEventArgs> eventQueue, CancellationToken token)
 {
     _stream      = stream;
     Id           = Guid.NewGuid();
     User         = name;
     Address      = address;
     _token       = token;
     _eventQueue  = eventQueue;
     _roleManager = new RoleManager(distributorRole, address, name);
 }
        public void DequeueEmpty()
        {
            EventQueue q = new EventQueue();

            Assert.IsNull(q.Dequeue(false));
        }
Example #33
0
 internal void SelfConnected()
 {
     CurrentStatus = ClientStatus.Connected;
     EventQueue.RemoveEvent(connectionTimeoutEvent);
     OnConnected?.Invoke();
 }
Example #34
0
 public ImageSheetUndoService(EventQueue dispatcher, UndoModel undo, DeckModel deck, SlideModel slide, ImageSheetModel sheet) : base(undo, deck, slide, sheet)
 {
     // There are currently no published properties of ImageSheetModel, other than those handled by the base class.
 }
        /// <summary>
        /// Retrieves the data from message processing custom request just to return custom response.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request">The request of concrete type.</param>
        /// <param name="service">The service is default parameter with default value null. If argument is not supplied service is created by the method.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">Request was not specified.</exception>
        public Response <T> RetrieveData <T>(Request <T> request, Service service = null, bool Async = true)
        {
            //Session session;
            Response <T> result = (Response <T>)Activator.CreateInstance(request.GetUnderlyingResponseType(), new object[] { request.RequestClass });
            Type         t      = typeof(T);

            Request blRequest;

            #region Initialize Service and Request if not provided

            /*if (request.GetSessionOptions() != null) { session = new Session(request.GetSessionOptions()); session.Start(); } // special session
             * else session = this.session;*/
            if (service == null)
            {
                service = session.GetService(request.GetService());
            }
            if (request != null)
            {
                blRequest = request.GetBloombergRequest(service);
            }
            else
            {
                throw new Exception("Request was not specified.");
            }
            #endregion

            CorrelationID requestID  = new CorrelationID(GenerateId());
            EventQueue    eventQueue = new EventQueue();
            // Generate request from object definition

            session.SendRequest(blRequest, eventQueue, requestID);

            bool continueToLoop = true;
            if (Async)
            {
                result.StartMessageProcessing();
                while (continueToLoop)
                {
                    Event eventObj = eventQueue.NextEvent();
                    if (eventObj.Type == Event.EventType.RESPONSE)
                    {
                        continueToLoop = false;
                    }
                    // Cracking messages

                    foreach (Message message in eventObj.GetMessages())
                    {
                        result.AddMessage(message);
                        //result.ProcessMessage(message);
                    }
                    if (result.ProcessingError != null)
                    {
                        break; throw result.ProcessingError;
                    }
                }
                result.StopMessageProcessing();
            }
            else
            {
                while (continueToLoop)
                {
                    Event eventObj = eventQueue.NextEvent();
                    if (eventObj.Type == Event.EventType.RESPONSE)
                    {
                        continueToLoop = false;
                    }
                    // Cracking messages

                    foreach (Message message in eventObj.GetMessages())
                    {
                        result.ProcessMessage(message);
                    }
                    if (result.ProcessingError != null)
                    {
                        break; throw result.ProcessingError;
                    }
                }
            }
            return(result);
        }
Example #36
0
        public void Run(String[] args)
        {
            if (!ParseCommandLine(args))
            {
                return;
            }

            SessionOptions sessionOptions = new SessionOptions();

            SessionOptions.ServerAddress[] servers = new SessionOptions.ServerAddress[d_hosts.Count];
            for (int i = 0; i < d_hosts.Count; ++i)
            {
                servers[i] = new SessionOptions.ServerAddress(d_hosts[i], d_port);
            }
            sessionOptions.ServerAddresses            = servers;
            sessionOptions.AutoRestartOnDisconnection = true;
            sessionOptions.NumStartAttempts           = d_hosts.Count;
            sessionOptions.DefaultSubscriptionService = d_service;
            sessionOptions.DefaultTopicPrefix         = "";     // normally defaults to "ticker"
            sessionOptions.AuthenticationOptions      = d_authOptions;

            System.Console.WriteLine("Connecting to port " + d_port + " on ");
            foreach (string host in d_hosts)
            {
                System.Console.WriteLine(host + " ");
            }
            Session session = new Session(sessionOptions);

            if (!session.Start())
            {
                System.Console.Error.WriteLine("Failed to start session.");
                return;
            }

            Identity identity = null;

            if (d_authOptions.Length != 0)
            {
                EventQueue tokenEventQueue = new EventQueue();
                session.GenerateToken(new CorrelationID(tokenEventQueue), tokenEventQueue);
                String    token = null;
                const int timeoutMilliSeonds = 10000;
                Event     eventObj           = tokenEventQueue.NextEvent(timeoutMilliSeonds);
                if (eventObj.Type == Event.EventType.TOKEN_STATUS)
                {
                    foreach (Message msg in eventObj)
                    {
                        System.Console.WriteLine(msg.ToString());
                        if (msg.MessageType == TOKEN_SUCCESS)
                        {
                            token = msg.GetElementAsString("token");
                        }
                    }
                }
                if (token == null)
                {
                    System.Console.WriteLine("Failed to get token");
                    System.Environment.Exit(1);
                }

                if (session.OpenService("//blp/apiauth"))
                {
                    Service authService = session.GetService("//blp/apiauth");
                    Request authRequest = authService.CreateAuthorizationRequest();
                    authRequest.Set("token", token);

                    EventQueue authEventQueue = new EventQueue();
                    identity = session.CreateIdentity();
                    session.SendAuthorizationRequest(authRequest, identity, authEventQueue, new CorrelationID(identity));

                    bool isAuthorized = false;
                    while (!isAuthorized)
                    {
                        eventObj = authEventQueue.NextEvent();
                        if (eventObj.Type == Event.EventType.RESPONSE ||
                            eventObj.Type == Event.EventType.PARTIAL_RESPONSE ||
                            eventObj.Type == Event.EventType.REQUEST_STATUS)
                        {
                            foreach (Message msg in eventObj)
                            {
                                System.Console.WriteLine(msg.ToString());
                                if (msg.MessageType == AUTHORIZATION_SUCCESS)
                                {
                                    isAuthorized = true;
                                    break;
                                }
                                else
                                {
                                    System.Console.Error.WriteLine("Not authorized: " + msg);
                                    System.Environment.Exit(1);
                                }
                            }
                        }
                    }
                }
            }

            List <Subscription> subscriptions = new List <Subscription>();

            // Short topic string; will get qualified by subscribe() using session
            // options: 'DefaultSubscriptionService' and 'DefaultTopicPrefix'
            // configured above
            String topic1 = "IBM Equity";

            // Fully qualified topic
            String topic2 = d_service + "/RHAT Equity";

            // Add a topic on unknown service to demonstrate event sequence
            String topic3 = d_service + "-unknown/RHAT Equity";

            subscriptions.Add(new Subscription(topic1, new CorrelationID(topic1)));
            subscriptions.Add(new Subscription(topic2, new CorrelationID(topic2)));
            subscriptions.Add(new Subscription(topic3, new CorrelationID(topic3)));
            session.Subscribe(subscriptions, identity);

            ProcessSubscriptionResponse(session);
        }
        private static async Task ProcessQueue(EventQueue queue)
        {
            if (queue.MainEvent != null)
            {
                try
                {
                    await queue.MainEvent.Handler().ConfigureAwait(false);

                    foreach (var cb in queue.Callbacks)
                    {
                        if (cb != null)
                        {
                            Task.Run(() => cb.TrySetResult(true)).Forget();
                        }
                    }
                }
                catch (Exception ex)
                {
                    foreach (var cb in queue.Callbacks)
                    {
                        if (cb != null)
                        {
                            Task.Run(() => cb.TrySetException(ex)).Forget();
                        }
                    }
                }
                return;
            }

            foreach (var keyspace in queue.Keyspaces)
            {
                if (keyspace.Value.RefreshKeyspaceEvent != null)
                {
                    try
                    {
                        await keyspace.Value.RefreshKeyspaceEvent.Handler().ConfigureAwait(false);

                        foreach (var cb in keyspace.Value.Events.Select(e => e.Callback).Where(e => e != null))
                        {
                            Task.Run(() => cb.TrySetResult(true)).Forget();
                        }
                    }
                    catch (Exception ex)
                    {
                        foreach (var cb in keyspace.Value.Events.Select(e => e.Callback).Where(e => e != null))
                        {
                            Task.Run(() => cb.TrySetException(ex)).Forget();
                        }
                    }

                    continue;
                }

                foreach (var ev in keyspace.Value.Events)
                {
                    try
                    {
                        await ev.KeyspaceEvent.Handler().ConfigureAwait(false);

                        if (ev.Callback != null)
                        {
                            Task.Run(() => ev.Callback.TrySetResult(true)).Forget();
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ev.Callback != null)
                        {
                            Task.Run(() => ev.Callback.TrySetException(ex)).Forget();
                        }
                    }
                }
            }
        }
Example #38
0
 public override void Self_OnAlertMessage(object sender, AlertMessageEventArgs e)
 {
     EventQueue.Enqueue(() => SendNewRegionEvent(SimEventType.SCRIPT, "On-Alert-Message", client.gridClient, e.Message));
 }
 public DataSeriesObject_bak(SubscribeInfo info, EventQueue queue)
 {
     EventQueue = queue;
     _info      = info;
     Init();
 }
Example #40
0
 public QueueConsumersManager(EventQueue queue)
 {
     _queue = queue;
     _consumers = Enumerable.Range(0, _numConsumerTasks).Select(i => new QueueConsumer(_queue)).ToList();          
 }
Example #41
0
 internal DataSeriesObject(IDataSeries series, DateTime dateTime1, DateTime dateTime2, EventQueue queue, DataProcessor processor)
 {
     this.series = series;
     eventQueue  = queue;
     if (processor == null)
     {
         this.processor = new DataProcessor();
     }
     else
     {
         this.processor = processor;
     }
     if (!(dateTime1 == DateTime.MinValue) && (dateTime1 >= series.DateTime1))
     {
         index1 = series.GetIndex(dateTime1, SearchOption.Next);
     }
     else
     {
         index1 = 0L;
     }
     if (!(dateTime2 == DateTime.MaxValue) && (dateTime2 <= series.DateTime2))
     {
         index2 = series.GetIndex(dateTime2);
     }
     else
     {
         index2 = series.Count - 1L;
     }
     current         = index1;
     progressDelta   = (int)Math.Ceiling(Count() / 100.0);
     progressCount   = progressDelta;
     progressPercent = 0;
 }
Example #42
0
        public static IInteractor Create(TcpClient tcpClient, DistributorRole distributorRole, EventQueue <InteractorEventArgs> eventQueue, CancellationToken token)
        {
            var stream = new NegotiateStream(tcpClient.GetStream());

            try
            {
                stream.AuthenticateAsServer();
            }
            catch (Exception error)
            {
                Log.Warn("Failed to negotiate stream", error);
                return(null);
            }

            var interactor = new Interactor(stream, stream.RemoteIdentity.Name, ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address, distributorRole, eventQueue, token);

            return(interactor);
        }
Example #43
0
        public static void Init()
        {
#if _NEWSTART_
            /** AGL.START Controlado */
            int Contador = 0;
            var NewList  = new List <VoidDelegate>
            {
                delegate()
                {
                    if (string.IsNullOrEmpty(_HostId) || string.IsNullOrEmpty(_SipIp))
                    {
                        List <string> ips = General.GetOperationalV4Ips();

                        if (string.IsNullOrEmpty(_SipIp))
                        {
                            _SipIp = (ips.Count > 0) ? ips[ips.Count - 1] : "127.0.0.1";
                        }

                        if (string.IsNullOrEmpty(_HostId))
                        {
                            _HostId = "PICT" + _SipIp.Substring(_SipIp.LastIndexOf('.') + 1);
                        }
                    }
                },
                delegate(){ InitSnmp(); },
                delegate(){ _WorkingThread = new EventQueue(); },
                delegate(){ _PublisherThread = new EventQueue(); },
                delegate()
                {
#if _AUDIOGENERIC_
                    // switch (Properties.Settings.Default.TipoAudioUsb)
                    switch (HwManager.AudioDeviceType)
                    {
                    case eAudioDeviceTypes.MICRONAS:
                        _HwManager = new MicronasHwManager();
                        break;

                    case eAudioDeviceTypes.CMEDIA:
                        _HwManager = new HidCMediaHwManager();
                        break;

                    case eAudioDeviceTypes.GENERIC_PTT:         // Cascos y Altavoces USB...
                        _HwManager = new HidGenericHwManager(true);
                        break;

                    case eAudioDeviceTypes.GENERIC:             // Cascos sin PTT y Altavoces USB...
                        _HwManager = new HidGenericHwManager(false);
                        break;

                    case eAudioDeviceTypes.SIMUL:               // Simulacion de Tarjetas HID
                        _HwManager = new SimCMediaHwManager();
                        break;

                    default:
                        throw new Exception("Dispositivos de Audio no Conocidos...");
                    }
#else
                    _HwManager = new HwManager();
#endif
                },
                delegate(){ _Registry = new TopRegistry(); },
                delegate(){ _CfgManager = new CfgManager(); },
                delegate(){ _SipManager = new SipManager(); },
                delegate(){ _MixerManager = new MixerManager(); },
                delegate(){ _TlfManager = new TlfManager(); },
                delegate(){ _LcManager = new LcManager(); },
                delegate(){ _RdManager = new RdManager(); },
                delegate(){ _RecorderManager = new RecorderManager(Settings.Default.GLP); },
                delegate(){ _ReplayManager = new ReplayManager(); }
            };
            var nNames = new List <string>
            {
                "_SipIp & _HostId", "InitSnmp", "_WorkingThread", "_PublisherThread", "HwManager",
                "Registry", "CfgManager", "SipManager", "MixedManager", "TlfManager", "LcManager", "RdManager", "RecorderManager", "ReplayManager"
            };
            foreach (VoidDelegate _new in NewList)
            {
                try
                {
                    _new();
                    Contador++;
                }
                catch (Exception x)
                {
                    _Logger.Fatal("Error en Rutina {1} de Creacion TOP: \n{0}", x.Message, nNames[Contador]);
                }
            }
#else
            if (string.IsNullOrEmpty(_HostId) || string.IsNullOrEmpty(_SipIp))
            {
                List <string> ips = General.GetOperationalV4Ips();

                if (string.IsNullOrEmpty(_SipIp))
                {
                    _SipIp = (ips.Count > 0) ? ips[ips.Count - 1] : "127.0.0.1";
                }

                if (string.IsNullOrEmpty(_HostId))
                {
                    _HostId = "PICT" + _SipIp.Substring(_SipIp.LastIndexOf('.') + 1);
                }
            }

            /* Inicializa la gestion SNMP */
            InitSnmp();

            _WorkingThread   = new EventQueue();
            _PublisherThread = new EventQueue();

#if _AUDIOGENERIC_
            /** AGL.CMEDIA */
            switch (Properties.Settings.Default.TipoAudioUsb)
            {
            case 0:         // IAU. Micronas.
                _HwManager = new MicronasHwManger();
                break;

            case 1:         // IAU. CMedia.
                _HwManager = new HidCMediaHwManager();
                break;

            case 2:         // Cascos y Altavoces USB...
                _HwManager = new HidGenericHwManager(true);
                break;

            case 3:         // Cascos sin PTT y Altavoces USB...
                _HwManager = new HidGenericHwManager(true);
                break;

            default:
                throw new Exception("HwManager de tipo Desconocido...");
            }
#else
            _HwManager = new HwManager();
#endif
            /** */

            _Registry     = new TopRegistry();
            _CfgManager   = new CfgManager();
            _SipManager   = new SipManager();
            _MixerManager = new MixerManager();
            _TlfManager   = new TlfManager();
            _LcManager    = new LcManager();
            _RdManager    = new RdManager();

            _RecorderManager = new RecorderManager();
            _ReplayManager   = new ReplayManager();
            /** */
#endif

#if _NEWSTART_
            /** AGL.START Controlado */
            Contador = 0;
            var InitList = new List <VoidDelegate>
            {
                delegate() { if (_HwManager != null)
                             {
                                 _HwManager.Init();
                             }
                },
                delegate() { if (_Registry != null)
                             {
                                 _Registry.Init();
                             }
                },
                delegate() { if (_CfgManager != null)
                             {
                                 _CfgManager.Init();
                             }
                },
                delegate() { if (_SipManager != null)
                             {
                                 _SipManager.Init();
                             }
                },
                delegate() { if (_MixerManager != null)
                             {
                                 _MixerManager.Init();
                             }
                },
                delegate() { if (_TlfManager != null)
                             {
                                 _TlfManager.Init();
                             }
                },
                delegate() { if (_LcManager != null)
                             {
                                 _LcManager.Init();
                             }
                },
                delegate() { if (_RdManager != null)
                             {
                                 _RdManager.Init();
                             }
                },
                delegate() { if (_RecorderManager != null)
                             {
                                 _RecorderManager.Init();
                             }
                }
            };
            var iNames = new List <string> {
                "HwManager", "Registry", "CfgManager", "SipManager", "MixedManager", "TlfManager", "LcManager", "RdManager", "RecorderManager"
            };
            foreach (VoidDelegate init in InitList)
            {
                try
                {
                    init();
                    Contador++;
                }
                catch (Exception x)
                {
                    _Logger.Fatal("Error en Rutina {1} de Inicializacion TOP: \n{0}", x.Message, iNames[Contador]);
                }
            }
#else
            _HwManager.Init();
            _Registry.Init();
            _CfgManager.Init();
            _SipManager.Init();
            _MixerManager.Init(_HwManager.ListaDispositivos);
            _TlfManager.Init();
            _LcManager.Init();
            _RdManager.Init();

            _RecorderManager.Init();
#endif
#if _NICMON_V0_
            /** */
            NetworkIFSupervisor.AutoReset = true;
            NetworkIFSupervisor.Elapsed  += NetworkChange_NetworkAvailabilityChanged;
            NetworkIFSupervisor.Enabled   = Settings.Default.SNMPEnabled == 1;
            _Logger.Info("TIMER NetworkIFSupervisor Arrancado...");
#else
            string jconfig = Properties.Settings.Default.LanTeamConfigs.Count > Properties.Settings.Default.LanTeamType ?
                             Properties.Settings.Default.LanTeamConfigs[Properties.Settings.Default.LanTeamType] : "";
            mon = new NicEventMonitor(jconfig,
                                      (lan, status) =>
            {
                string oid = lan == 0 ? Settings.Default.NetworkIF_1_Oid : Settings.Default.NetworkIF_2_Oid;
                SnmpIntObject.Get(oid).Value = (int)status;

                _Logger.Info(String.Format("Notificado cambio en LAN {0} => {1}", lan, status));
            }, (m, x) =>
            {
                _Logger.Error(String.Format("Error Message: {0}", m));
            } /*, filePath*/);
            _Logger.Info("NetworkIFSupervisor Arrancado...");
#endif

            /** 20170309. AGL. Supervision Cliente NTP. */
            NtpClientSupervisor.AutoReset = true;
            NtpClientSupervisor.Elapsed  += NtpClientSupervisor_tick;
            NtpClientSupervisor.Enabled   = Settings.Default.SNMPEnabled == 1;
            _Logger.Info("TIMER NtpClientSupervisor Arrancado...");
            /*****************/
        }
Example #44
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="dispatcher">The event queue</param>
 /// <param name="model">The model</param>
 public RedoToolBarButton(EventQueue dispatcher, PresenterModel model) : base(dispatcher, model)
 {
     // TODO: Dynamically change the ToolTipText depending on what type of change will be redone.
     this.ToolTipText = Strings.RedoTooltipText;
 }
Example #45
0
File: Base.cs Project: vokac/F2B
 protected void Produce(EventEntry item, string processor = null, EventQueue.Priority priority = EventQueue.Priority.Medium)
 {
     Service.Produce(item, processor, priority);
 }
 public EventQueueTests()
 {
     this.Q = new EventQueue(EventQueues.Ec2Events);
 }
Example #47
0
        public void Run()
        {
            this.thread = new Thread(() =>
            {
                Console.WriteLine($"{DateTime.Now} Data simulator thread started");
                if (!IsConnected)
                    Connect();

                var q = new EventQueue(EventQueueId.Data, EventQueueType.Master, EventQueuePriority.Normal, 16, null)
                {
                    Name = "Data Simulator Start Queue",
                    IsSynched = true
                };
                q.Enqueue(new OnQueueOpened(q));
                q.Enqueue(new OnSimulatorStart(DateTime1, DateTime2, 0));
                q.Enqueue(new OnQueueClosed(q));
                this.framework.EventBus.DataPipe.Add(q);

                this.running = true;
                this.exit = false;
                while (!this.exit)
                {
                    LinkedListNode<DataSeriesObject> lastNode = null;
                    var node = this.emitters.First;
                    while (node != null)
                    {
                        var emitter = node.Data;
                        if (!emitter.Done)
                        {
                            if (emitter.Enqueue())
                                this.objCount++;
                            lastNode = node;
                        }
                        else
                        {
                            if (lastNode == null)
                                this.emitters.First = node.Next;
                            else
                                lastNode.Next = node.Next;
                            this.emitters.Count--;
                            emitter.dataQueue.Enqueue(new OnQueueClosed(emitter.dataQueue));
                        }
                        node = node.Next;
                    }
                }
                this.exit = false;
                this.running = false;

                Console.WriteLine($"{DateTime.Now} Data simulator thread stopped");
            })
            {
                Name = "Data Simulator Thread",
                IsBackground = true
            };
            this.thread.Start();
        }
 public ProjectLoadedListener(EventQueue eventQueue)
 {
     _eventQueue = eventQueue;
 }
Example #49
0
 public DataSeriesObject(IDataSeries series, DateTime dateTime1, DateTime dateTime2, EventQueue dataQueue, DataProcessor processor)
 {
     this.queue = new EventQueue(EventQueueId.All, EventQueueType.Master, EventQueuePriority.Normal, 128, null);
     this.series = series;
     this.dataQueue = dataQueue;
     this.processor = processor ?? new DataProcessor();
     this.index1 = dateTime1 == DateTime.MinValue || dateTime1 < series.DateTime1 ? 0 : series.GetIndex(dateTime1, SearchOption.Next);
     this.index2 = dateTime2 == DateTime.MaxValue || dateTime2 > series.DateTime2 ? series.Count - 1 : series.GetIndex(dateTime2, SearchOption.Prev);
     this.current = this.index1;
     this.delta = (int)Math.Ceiling((this.index2 - this.index1 + 1) / 100.0);
     this.count = this.delta;
     this.percent = 0;
 }
Example #50
0
 public void SetUp()
 {
     theQueue   = new EventQueue <FakeTopic>();
     theChannel = new Channel <FakeTopic>(theQueue);
 }
Example #51
0
 public static ICoroutineEvent DequeueEvent(this EventQueue eventQueue)
 {
     Assert.True(eventQueue.TryDequeue(out IEvent ev));
     Assert.IsAssignableFrom <ICoroutineEvent>(ev);
     return(ev as ICoroutineEvent);
 }
Example #52
0
 public void BeforeTest()
 {
     mockStrategy = new Mock <IEventQueueStorageStrategy <TestEvent> >();
     queue        = new EventQueueImp(mockStrategy.Object);
 }
Example #53
0
 public void ClearQueue()
 {
     m_TimerQueued = false;
     EventQueue.Clear();
 }
        private bool Authorize(
            Service authService,
            Identity identity,
            ProviderSession session,
            CorrelationID cid)
        {
            lock (d_authorizationStatus)
            {
                d_authorizationStatus[cid] = AuthorizationStatus.WAITING;
            }
            EventQueue tokenEventQueue = new EventQueue();

            try
            {
                session.GenerateToken(new CorrelationID(tokenEventQueue), tokenEventQueue);
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
                return(false);
            }
            String    token = null;
            const int timeoutMilliSeconds = 10000;
            Event     eventObj            = tokenEventQueue.NextEvent(timeoutMilliSeconds);

            if (eventObj.Type == Event.EventType.TOKEN_STATUS ||
                eventObj.Type == Event.EventType.REQUEST_STATUS)
            {
                foreach (Message msg in eventObj)
                {
                    System.Console.WriteLine(msg.ToString());
                    if (msg.MessageType == TOKEN_SUCCESS)
                    {
                        token = msg.GetElementAsString("token");
                    }
                }
            }
            if (token == null)
            {
                System.Console.WriteLine("Failed to get token");
                return(false);
            }

            Request authRequest = authService.CreateAuthorizationRequest();

            authRequest.Set("token", token);

            lock (d_authorizationStatus)
            {
                session.SendAuthorizationRequest(authRequest, identity, cid);

                DateTime startTime = System.DateTime.Now;
                int      waitTime  = 10 * 1000;           // 10 seconds in milliseconds
                while (true)
                {
                    Monitor.Wait(d_authorizationStatus, waitTime);
                    if (d_authorizationStatus[cid] != AuthorizationStatus.WAITING)
                    {
                        return(d_authorizationStatus[cid] == AuthorizationStatus.AUTHORIZED);
                    }
                    waitTime -= (int)(System.DateTime.Now - startTime).TotalMilliseconds;
                    if (waitTime <= 0)
                    {
                        return(false);
                    }
                }
            }
        }
        public void HostedCacheServer_PchcServer_BatchedOffer_ContentRetrieved()
        {
            CheckApplicability();

            EventQueue eventQueue = new EventQueue(BaseTestSite);
            eventQueue.Timeout = testConfig.Timeout;

            byte[] content = TestUtility.GenerateRandomArray(ContentInformationUtility.DefaultBlockSize);
            Content_Information_Data_Structure_V2 contentInformationV2 = contentInformationUtility.CreateContentInformationV2();

            BaseTestSite.Log.Add(
                LogEntryKind.Debug,
                "Start PCCRR server to be ready to serve content to hosted cache server");

            using (PccrrTestServerV2 pccrrTestServerV2 = new PccrrTestServerV2())
            {
                pccrrTestServerV2.Start(
                    testConfig.ClientContentRetrievalListenPort,
                    CryptoAlgoId_Values.AES_128,
                    contentInformationV2,
                    content,
                    eventQueue);

                PCHCClient pchcClient = new PCHCClient(
                    TransferProtocol.HTTP,
                    testConfig.HostedCacheServerComputerName,
                    testConfig.HostedCacheServerHTTPListenPort,
                    PchcConsts.HttpUrl,
                    testConfig.DomainName,
                    testConfig.UserName,
                    testConfig.UserPassword);

                BaseTestSite.Log.Add(
                LogEntryKind.Debug,
                "Directly Supply segment info to hosted cache server");

                var batchedOfferMessage = pchcClient.CreateBatchedOfferMessage(
                    testConfig.ClientContentRetrievalListenPort,
                    contentInformationV2);
                pchcClient.SendBatchedOfferMessage(batchedOfferMessage);

                BaseTestSite.Log.Add(
                    LogEntryKind.Debug,
                    "Make sure all the segments in chunk 0 is retrieved by hosted cache server");

                int blockCount = 0;
                int totalBlockCount = contentInformationV2.GetBlockCount();
                TestUtility.DoUntilSucceed(delegate()
                {
                    eventQueue.Expect<MessageArrivedEventArgs>(typeof(PccrrServer).GetEvent("MessageArrived"), delegate(System.Net.IPEndPoint sender, PccrrPacket pccrrPacket)
                    {
                        var pccrrGetBlksRequest = pccrrPacket as PccrrGETBLKSRequestPacket;

                        if (pccrrGetBlksRequest != null)
                        {
                            blockCount++;
                        }
                    });
                    return blockCount == totalBlockCount;
                }, TimeSpan.MaxValue, TimeSpan.Zero);

                BaseTestSite.Log.Add(
                    LogEntryKind.Debug,
                    "Wait until cache is available on hosted cache server");

                TestUtility.DoUntilSucceed(() => sutControlAdapter.IsLocalCacheExisted(testConfig.HostedCacheServerComputerFQDNOrNetBiosName), testConfig.Timeout, testConfig.RetryInterval);

                BaseTestSite.Log.Add(
                    LogEntryKind.Debug,
                    "Re-supply segment info to hosted cache server");

                var batchedOfferResponse = pchcClient.SendBatchedOfferMessage(batchedOfferMessage);

                BaseTestSite.Assert.AreEqual(
                    RESPONSE_CODE.OK,
                    batchedOfferResponse.ResponseCode,
                    "Hosted cache server should return OK to batched offer message");
            }
        }
Example #56
0
        /// <summary>
        /// Process the next event queued for this script
        /// </summary>
        /// <returns></returns>
        public object EventProcessor()
        {
            // We check here as the thread stopping this instance from running may itself hold the m_Script lock.
            if (!Running)
            {
                return(0);
            }

            lock (m_Script)
            {
                //                m_log.DebugFormat("[XEngine]: EventProcessor() invoked for {0}.{1}", PrimName, ScriptName);

                if (Suspended)
                {
                    return(0);
                }

                EventParams data = null;

                lock (EventQueue)
                {
                    data = (EventParams)EventQueue.Dequeue();
                    if (data == null) // Shouldn't happen
                    {
                        if (EventQueue.Count > 0 && Running && !ShuttingDown)
                        {
                            m_CurrentWorkItem = Engine.QueueEventHandler(this);
                        }
                        else
                        {
                            m_CurrentWorkItem = null;
                        }
                        return(0);
                    }

                    if (data.EventName == "timer")
                    {
                        m_TimerQueued = false;
                    }
                    if (data.EventName == "control")
                    {
                        if (m_ControlEventsInQueue > 0)
                        {
                            m_ControlEventsInQueue--;
                        }
                    }
                    if (data.EventName == "collision")
                    {
                        m_CollisionInQueue = false;
                    }
                }

                if (DebugLevel >= 2)
                {
                    m_log.DebugFormat(
                        "[SCRIPT INSTANCE]: Processing event {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}",
                        data.EventName,
                        ScriptName,
                        Part.Name,
                        Part.LocalId,
                        Part.ParentGroup.Name,
                        Part.ParentGroup.UUID,
                        Part.AbsolutePosition,
                        Part.ParentGroup.Scene.Name);
                }

                m_DetectParams = data.DetectParams;

                if (data.EventName == "state") // Hardcoded state change
                {
                    State = data.Params[0].ToString();

                    if (DebugLevel >= 1)
                    {
                        m_log.DebugFormat(
                            "[SCRIPT INSTANCE]: Changing state to {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}",
                            State,
                            ScriptName,
                            Part.Name,
                            Part.LocalId,
                            Part.ParentGroup.Name,
                            Part.ParentGroup.UUID,
                            Part.AbsolutePosition,
                            Part.ParentGroup.Scene.Name);
                    }

                    AsyncCommandManager.UnregisterScriptFacilities(Engine,
                                                                   LocalID, ItemID);

                    Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State));
                }
                else
                {
                    if (Engine.World.PipeEventsForScript(LocalID) ||
                        data.EventName == "control") // Don't freeze avies!
                    {
                        //                m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}",
                        //                        PrimName, ScriptName, data.EventName, State);

                        try
                        {
                            m_CurrentEvent = data.EventName;
                            m_EventStart   = DateTime.Now;
                            m_InEvent      = true;

                            int start = Util.EnvironmentTickCount();

                            // Reset the measurement period when we reach the end of the current one.
                            if (start - MeasurementPeriodTickStart > MaxMeasurementPeriod)
                            {
                                MeasurementPeriodTickStart = start;
                            }

                            m_Script.ExecuteEvent(State, data.EventName, data.Params);

                            MeasurementPeriodExecutionTime += Util.EnvironmentTickCount() - start;

                            m_InEvent      = false;
                            m_CurrentEvent = String.Empty;

                            if (m_SaveState)
                            {
                                // This will be the very first event we deliver
                                // (state_entry) in default state
                                //
                                SaveState(m_Assembly);

                                m_SaveState = false;
                            }
                        }
                        catch (EventAbortException)
                        {
                        }
                        catch (Exception e)
                        {
                            //                            m_log.DebugFormat(
                            //                                "[SCRIPT] Exception in script {0} {1}: {2}{3}",
                            //                                ScriptName, ItemID, e.Message, e.StackTrace);

                            m_InEvent      = false;
                            m_CurrentEvent = String.Empty;

                            if ((!(e is TargetInvocationException) ||
                                 (!(e.InnerException is SelfDeleteException) &&
                                  !(e.InnerException is ScriptDeleteException) &&
                                  !(e.InnerException is ScriptCoopStopException))) &&
                                !(e is ThreadAbortException))
                            {
                                try
                                {
                                    // DISPLAY ERROR INWORLD
                                    string text = FormatException(e);

                                    if (text.Length > 1000)
                                    {
                                        text = text.Substring(0, 1000);
                                    }
                                    Engine.World.SimChat(Utils.StringToBytes(text),
                                                         ChatTypeEnum.DebugChannel, 2147483647,
                                                         Part.AbsolutePosition,
                                                         Part.Name, Part.UUID, false);

                                    m_log.Debug(string.Format(
                                                    "[SCRIPT INSTANCE]: Runtime error in script {0}, part {1} {2} at {3} in {4} ",
                                                    ScriptName,
                                                    PrimName,
                                                    Part.UUID,
                                                    Part.AbsolutePosition,
                                                    Part.ParentGroup.Scene.Name),
                                                e);
                                }
                                catch (Exception)
                                {
                                }
                                // catch (Exception e2) // LEGIT: User Scripting
                                // {
                                // m_log.Error("[SCRIPT]: "+
                                //           "Error displaying error in-world: " +
                                //         e2.ToString());
                                //    m_log.Error("[SCRIPT]: " +
                                //              "Errormessage: Error compiling script:\r\n" +
                                //            e.ToString());
                                // }
                            }
                            else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException))
                            {
                                m_InSelfDelete = true;
                                Engine.World.DeleteSceneObject(Part.ParentGroup, false);
                            }
                            else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException))
                            {
                                m_InSelfDelete = true;
                                Part.Inventory.RemoveInventoryItem(ItemID);
                            }
                            else if ((e is TargetInvocationException) && (e.InnerException is ScriptCoopStopException))
                            {
                                if (DebugLevel >= 1)
                                {
                                    m_log.DebugFormat(
                                        "[SCRIPT INSTANCE]: Script {0}.{1} in event {2}, state {3} stopped co-operatively.",
                                        PrimName, ScriptName, data.EventName, State);
                                }
                            }
                        }
                    }
                }

                // If there are more events and we are currently running and not shutting down, then ask the
                // script engine to run the next event.
                lock (EventQueue)
                {
                    EventsProcessed++;

                    if (EventQueue.Count > 0 && Running && !ShuttingDown)
                    {
                        m_CurrentWorkItem = Engine.QueueEventHandler(this);
                    }
                    else
                    {
                        m_CurrentWorkItem = null;
                    }
                }

                m_DetectParams = null;

                return(0);
            }
        }
 internal virtual void Clear() {
     ObstacleTree.Clear();
     eventQueue = new EventQueue();
     HorizontalScanSegments = new ScanSegmentTree(ScanDirection.HorizontalInstance);
     VerticalScanSegments = new ScanSegmentTree(ScanDirection.VerticalInstance);
     VisibilityGraph = null;
 }
Example #58
0
        /// <summary>
        /// Post an event to this script instance.
        /// </summary>
        /// <remarks>
        /// The request to run the event is sent
        /// </remarks>
        /// <param name="data"></param>
        public void PostEvent(EventParams data)
        {
            //            m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}",
            //                        PrimName, ScriptName, data.EventName, State);

            if (!Running)
            {
                return;
            }

            // If min event delay is set then ignore any events untill the time has expired
            // This currently only allows 1 event of any type in the given time period.
            // This may need extending to allow for a time for each individual event type.
            if (m_eventDelayTicks != 0)
            {
                if (DateTime.Now.Ticks < m_nextEventTimeTicks)
                {
                    return;
                }
                m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks;
            }

            lock (EventQueue)
            {
                if (EventQueue.Count >= m_MaxScriptQueue)
                {
                    return;
                }

                if (data.EventName == "timer")
                {
                    if (m_TimerQueued)
                    {
                        return;
                    }
                    m_TimerQueued = true;
                }

                if (data.EventName == "control")
                {
                    int held = ((LSL_Types.LSLInteger)data.Params[1]).value;
                    // int changed = ((LSL_Types.LSLInteger)data.Params[2]).value;

                    // If the last message was a 0 (nothing held)
                    // and this one is also nothing held, drop it
                    //
                    if (m_LastControlLevel == held && held == 0)
                    {
                        return;
                    }

                    // If there is one or more queued, then queue
                    // only changed ones, else queue unconditionally
                    //
                    if (m_ControlEventsInQueue > 0)
                    {
                        if (m_LastControlLevel == held)
                        {
                            return;
                        }
                    }

                    m_LastControlLevel = held;
                    m_ControlEventsInQueue++;
                }

                if (data.EventName == "collision")
                {
                    if (m_CollisionInQueue)
                    {
                        return;
                    }
                    if (data.DetectParams == null)
                    {
                        return;
                    }

                    m_CollisionInQueue = true;
                }

                EventQueue.Enqueue(data);

                if (m_CurrentWorkItem == null)
                {
                    m_CurrentWorkItem = Engine.QueueEventHandler(this);
                }
            }
        }
Example #59
0
 public QueueConsumer(EventQueue queue)
 {
     _queue = queue;
 }
Example #60
0
    public void TriggerComponentTest_navigationNodeMove()
    {
        // Initializing trigger Entity
        Entity l_testTriggerEntity = Entity.alloc();

        l_testTriggerEntity.EntityGameWorld = EntityGameWorld.build(TransformComponent.alloc());

        EntityComponent.add_component(l_testTriggerEntity, NavigationEngineTestTriggerComponent.alloc());
        EntityComponent.add_component(l_testTriggerEntity, Locomotion.alloc(new LocomotionData()
        {
            Speed = float.MaxValue * 0.1f
        }));

        // We warp the l_testTriggeredEntity to a random NavigationNode
        EventQueue.enqueueEvent(
            TestEventQueue,
            NavigationNodeWarpEntityEvent.alloc(
                l_testTriggerEntity,
                NavigationGraphAlgorithm.pickRandomNode(NavigationGraphContainer.UniqueNavigationGraph)
                )
            );

        EventQueue.iterate(TestEventQueue);

        // We create the Entity that will be involved in the trigger
        Entity l_entity = Entity.alloc();

        l_entity.EntityGameWorld = EntityGameWorld.build(TransformComponent.alloc());

        EntityComponent.add_component(l_entity, Locomotion.alloc(new LocomotionData()
        {
            Speed = float.MaxValue * 0.1f
        }));

        ActionPointData l_actionPointdata = new ActionPointData()
        {
            InitialActionPoints = 999f, CurrentActionPoints = 999f
        };

        EntityComponent.add_component(l_entity, ActionPoint.alloc(ref l_actionPointdata));

        var l_entityNavigationNodeEnumerator =
            NavigationGraphAlgorithm.getReachableNeighborNavigationNodes(NavigationGraphContainer.UniqueNavigationGraph, l_testTriggerEntity.CurrentNavigationNode, NavigationGraphFlag.CURRENT).GetEnumerator();

        l_entityNavigationNodeEnumerator.MoveNext();

        EventQueue.enqueueEvent(
            TestEventQueue,
            NavigationNodeWarpEntityEvent.alloc(
                l_entity,
                l_entityNavigationNodeEnumerator.Current
                )
            );


        NavigationNodeMoveEvent l_navigationNodeMoveEvent = NavigationNodeMoveEvent.alloc(l_entity, l_testTriggerEntity.CurrentNavigationNode);

        EventQueue.enqueueEvent(
            TestEventQueue,
            l_navigationNodeMoveEvent
            );

        while (!l_navigationNodeMoveEvent.IsCompleted())
        {
            LocomotionSystemV2Container.Tick(1.0f);
            EventQueue.iterate(TestEventQueue);
        }

        NavigationEngineTestTriggerComponent l_triggerComponent = EntityComponent.get_component <NavigationEngineTestTriggerComponent>(l_testTriggerEntity);

        Assert.IsTrue(l_triggerComponent.IsTriggered);
        Assert.IsTrue(l_triggerComponent.TriggeredEntity == l_entity);
    }