Esempio n. 1
0
        /// <summary>
        /// Enqueues an event, to be handled by subscribers sometime later.
        /// There is no guarantee that the event will end up being handled
        /// (e.g. suspended or shut down queues silently ignore events,
        /// or the application may be terminated beforehand).
        /// </summary>
        /// <param name="eventQueue">The event queue to add the event to.</param>
        /// <param name="evnt">The event to enqueue.</param>
        /// <param name="onHandled">An optional delegate to invoke sometime after the event finished being handled. It may not get called, if the event queue is suspended or being shut down. Check the return value to know whether you can reasonably expect it.</param>
        /// <param name="file">The source file of the caller.</param>
        /// <param name="member">The method or property name of the caller to this method.</param>
        /// <param name="line">The line number in <paramref name="file"/>.</param>
        /// <returns><c>true</c> if the event was enqueued successfully and you can expect a callback once it's done being handled; otherwise, <c>false</c>.</returns>
        public static bool Enqueue(
            this IEventQueue eventQueue,
            EventBase evnt,
            EventHandledDelegate onHandled,
            [CallerFilePath] string file     = "",
            [CallerMemberName] string member = "",
            [CallerLineNumber] int line      = 0)
        {
            if (onHandled.NullReference())
            {
                return(eventQueue.Enqueue(evnt, file, member, line));
            }

            var finishedEvent    = new FinishedEvent(evnt);
            var finishedListener = new FinishedEventHandler(eventQueue, finishedEvent.Index, onHandled);

            eventQueue.Subscribers.Add(finishedListener, weakRef: false);

            var eventsAdded = eventQueue.Enqueue(evnt, file, member, line) &&
                              eventQueue.Enqueue(finishedEvent, file, member, line); // doesn't even get called if the first one fails, which is what we want.

            if (!eventsAdded)
            {
                eventQueue.Subscribers.Remove(finishedListener);
            }

            return(eventsAdded);
        }
Esempio n. 2
0
        // Collects some performance counters
        protected virtual void ReadPerfCountersEvents()
        {
            try
            {
                while (!stopped)
                {
                    CounterWorkloadEvent evt = new CounterWorkloadEvent();
                    evt.Type      = WorkloadEvent.EventType.PerformanceCounter;
                    evt.StartTime = DateTime.Now;

                    evt.Counters.Add(
                        CounterWorkloadEvent.CounterNameEnum.AVG_CPU_USAGE,
                        GetLastCPUUsage()
                        );

                    Events.Enqueue(evt);

                    Thread.Sleep(StatsCollectionIntervalSeconds * 1000); // 1 minute
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                logger.Error(ex.StackTrace);

                if (ex.InnerException != null)
                {
                    logger.Error(ex.InnerException.Message);
                }
            }
        }
        public void OnTemplateChanged(string templatePath, bool force = false)
        {
            Log.Debug("{0} queued {1}", GenerationType.Template, templatePath);

            ErrorList.Clear();

            ThreadHelper.JoinableTaskFactory.Run(async() =>
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                var projectItem = _dte.Solution.FindProjectItem(templatePath);

                var template = _templateController.GetTemplate(projectItem);

                if (force == false && ExtensionPackage.Instance.RenderOnSave == false)
                {
                    Log.Debug("Render skipped {0}", templatePath);
                    return;
                }

                var filesToRender = template.GetFilesToRender();
                Log.Debug(" Will Check/Render {0} .cs files in referenced projects", filesToRender.Count);


                // Delay to wait for Roslyn to refresh the current Workspace after a change.
                await Task.Delay(1000).ConfigureAwait(true);
                _eventQueue.Enqueue(() =>
                {
                    var stopwatch = Stopwatch.StartNew();

                    foreach (var path in filesToRender)
                    {
                        var metadata = _metadataProvider.GetFile(path, template.Settings, null);
                        if (metadata == null)
                        {
                            // the cs-file was found, but the build-action is not set to compile.
                            continue;
                        }

                        var file = new FileImpl(metadata);

                        template.RenderFile(file);

                        if (template.HasCompileException)
                        {
                            break;
                        }
                    }

                    template.SaveProjectFile();

                    stopwatch.Stop();
                    Log.Debug("{0} processed {1} in {2}ms", GenerationType.Template, templatePath,
                              stopwatch.ElapsedMilliseconds);
                });
            });
        }
Esempio n. 4
0
        public async Task <bool> Run(CancellationToken token)
        {
            var client = await _broker.Connect();

            if (!client.Valid)
            {
                throw new InvalidOperationException("Could not connect to Telegram.");
            }

            _log.Information("Current user is {0}.", client.User.Username);

            _broker.Client.OnMessage += (sender, args) => {
                if (args.Message.Type == Bot.Types.Enums.MessageType.TextMessage)
                {
                    _queue.Enqueue(new MessageEvent(_broker)
                    {
                        Bot     = client.User,
                        Message = new Message {
                            Text = args.Message.Text, User = args.Message.GetUser()
                        },
                        Room = args.Message.GetRoom()
                    });
                }
            };

            _broker.Client.StartReceiving(token);
            return(true);
        }
Esempio n. 5
0
        public void OnGetScriptRunning(IClientAPI controllingClient,
                                       UUID objectID, UUID itemID)
        {
            uint localID = m_ScriptManager.GetLocalID(itemID);

            if (localID == 0)
            {
                return;
            }

            InstanceData id = m_ScriptManager.GetScript(localID, itemID);

            if (id == null)
            {
                return;
            }

            IEventQueue eq = World.RequestModuleInterface <IEventQueue>();

            if (eq == null)
            {
                controllingClient.SendScriptRunningReply(objectID, itemID,
                                                         id.Running);
            }
            else
            {
                eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, id.Running, true),
                           controllingClient.AgentId);
            }
        }
Esempio n. 6
0
        public async Task <bool> Run(CancellationToken token)
        {
            var client = await _broker.Connect();

            if (!client.IsValid)
            {
                throw new InvalidOperationException("Could not connect to Discord.");
            }
            _log.Information("Connected to Discord.");
            _broker.Client.MessageReceived += (sender, args) =>
            {
                _log.Verbose("Discord: Message received, adding event to queue.");
                _queue.Enqueue(new MessageEvent(_broker)
                {
                    Bot     = client.Bot,
                    Message = new Dotbot.Models.Message {
                        Text = args.Message.Text, User = args.User.ToBotUser()
                    },
                    Room = args.Channel.ToRoom()
                });
            };
            _log.Verbose("Discord: Adapter started, listening for messages.");
            token.WaitHandle.WaitOne(Timeout.Infinite);
            return(true);
        }
Esempio n. 7
0
    public virtual bool Publish <TEvent>(TEvent @event)
        where TEvent : class, IEventBase
    {
        var queueName = _options.EventQueueNameResolver.Invoke(@event.GetType()) ?? "events";

        return(_eventQueue.Enqueue(queueName, @event));
    }
        void ChatterBoxSessionStartReplyViaCaps(IClientAPI remoteClient, string groupName, UUID groupID)
        {
            if (m_debugEnabled)
            {
                m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
            }

            OSDMap moderatedMap = new OSDMap(4);

            moderatedMap.Add("voice", OSD.FromBoolean(false));

            OSDMap sessionMap = new OSDMap(4);

            sessionMap.Add("moderated_mode", moderatedMap);
            sessionMap.Add("session_name", OSD.FromString(groupName));
            sessionMap.Add("type", OSD.FromInteger(0));
            sessionMap.Add("voice_enabled", OSD.FromBoolean(false));

            OSDMap bodyMap = new OSDMap(4);

            bodyMap.Add("session_id", OSD.FromUUID(groupID));
            bodyMap.Add("temp_session_id", OSD.FromUUID(groupID));
            bodyMap.Add("success", OSD.FromBoolean(true));
            bodyMap.Add("session_info", sessionMap);

            IEventQueue queue = remoteClient.Scene.RequestModuleInterface <IEventQueue>();

            queue?.Enqueue(queue.BuildEvent("ChatterBoxSessionStartReply", bodyMap), remoteClient.AgentId);
        }
Esempio n. 9
0
 /// <summary>
 /// Enqueues a <see cref="ShuttingDownEvent"/>.
 /// </summary>
 /// <param name="eventQueue">The <see cref="IEventQueue"/> to use.</param>
 /// <param name="file">The source file of the caller.</param>
 /// <param name="member">The method or property name of the caller to this method.</param>
 /// <param name="line">The line number in <paramref name="file"/>.</param>
 /// <returns><c>true</c> if the event was enqueued successfully; otherwise, <c>false</c>.</returns>
 public static bool BeginShutdown(
     this IEventQueue eventQueue,
     [CallerFilePath] string file     = "",
     [CallerMemberName] string member = "",
     [CallerLineNumber] int line      = 0)
 {
     return(eventQueue.Enqueue(new ShuttingDownEvent(), file, member, line));
 }
Esempio n. 10
0
        protected Task WriteMessageAsync(IList <LogMessage> messages)
        {
            foreach (var message in messages)
            {
                _eventQueue.Enqueue(message);
            }

            return(Task.CompletedTask);
        }
        public void SendConsoleOutput(UUID agentID, string message)
        {
            OSD         osd = OSD.FromString(message);
            IEventQueue eq  = m_scene.RequestModuleInterface <IEventQueue>();

            if (eq != null)
            {
                eq.Enqueue(EventQueueHelper.BuildEvent("SimConsoleResponse", osd), agentID);
            }
        }
Esempio n. 12
0
        public void SendConsoleOutput(UUID agentID, string message)
        {
            if (!m_scene.TryGetScenePresence(agentID, out ScenePresence sp) || sp.IsChildAgent || sp.IsDeleted)
            {
                RemoveConsole(agentID);
                return;
            }

            m_eventQueue.Enqueue(m_eventQueue.BuildEvent("SimConsoleResponse", OSD.FromString(message)), agentID);
            OnConsoleMessage?.Invoke(agentID, message);
        }
Esempio n. 13
0
        protected void Apply(IDomainEvent @event, bool isNew = true)
        {
            Version++;
            @event.Version = Version;

            CallEventHandler(@event);

            if (isNew)
            {
                _eventQueue.Enqueue(@event);
            }
        }
Esempio n. 14
0
        public void OnTemplateChanged(string templatePath)
        {
            Log.Debug("{0} queued {1}", GenerationType.Template, templatePath);

            ErrorList.Clear();

            var projectItem = _dte.Solution.FindProjectItem(templatePath);

            var template      = _templateController.GetTemplate(projectItem);
            var filesToRender = template.GetFilesToRender();

            Log.Debug(" Will Check/Render {0} .cs files in referenced projects", filesToRender.Count);

            // Delay to wait for Roslyn to refresh the current Workspace after a change.
            Task.Delay(1000).ContinueWith(task =>
            {
                _eventQueue.Enqueue(() =>
                {
                    var stopwatch = Stopwatch.StartNew();

                    foreach (var path in filesToRender)
                    {
                        var metadata = _metadataProvider.GetFile(path);
                        var file     = new FileImpl(metadata);

                        template.RenderFile(file);

                        if (template.HasCompileException)
                        {
                            break;
                        }
                    }

                    template.SaveProjectFile();

                    stopwatch.Stop();
                    Log.Debug("{0} processed {1} in {2}ms", GenerationType.Template, templatePath, stopwatch.ElapsedMilliseconds);
                });
            });
        }
Esempio n. 15
0
        public void SendConsoleOutput(UUID agentID, string message)
        {
            OSD osd = OSD.FromString(message);

            m_eventQueue.Enqueue(EventQueueHelper.BuildEvent("SimConsoleResponse", osd), agentID);

            ConsoleMessage handlerConsoleMessage = OnConsoleMessage;

            if (handlerConsoleMessage != null)
            {
                handlerConsoleMessage(agentID, message);
            }
        }
Esempio n. 16
0
 /// <inheritdoc />
 public override void Enqueue(T e)
 {
     if (!ReferenceEquals(e, null))
     {
         if (e is ClearQueueEvent)
         {
             Clear();
         }
         else
         {
             _events.Enqueue(e);
         }
     }
 }
Esempio n. 17
0
 void EventManager_OnGetScriptRunning(OpenSim.Framework.IClientAPI controllingClient,
                                      OpenMetaverse.UUID objectID, OpenMetaverse.UUID itemID)
 {
     _exeScheduler.PostScriptInfoRequest(new ScriptInfoRequest(itemID, ScriptInfoRequest.Type.ScriptRunningRequest,
                                                               delegate(ScriptInfoRequest req)
     {
         IEventQueue eq = World.RequestModuleInterface <IEventQueue>();
         if (eq != null)
         {
             eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, req.IsRunning, false),
                        controllingClient.AgentId);
         }
     }
                                                               ));
 }
Esempio n. 18
0
        void SendGroupMembershipInfoViaCaps(IClientAPI remoteClient, GroupMembershipData[] data)
        {
            m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);

            OSDArray AgentData    = new OSDArray(1);
            OSDMap   AgentDataMap = new OSDMap(1);

            AgentDataMap.Add("AgentID", OSD.FromUUID(remoteClient.AgentId));
            AgentData.Add(AgentDataMap);


            OSDArray GroupData    = new OSDArray(data.Length);
            OSDArray NewGroupData = new OSDArray(data.Length);

            foreach (GroupMembershipData membership in data)
            {
                OSDMap GroupDataMap    = new OSDMap(6);
                OSDMap NewGroupDataMap = new OSDMap(1);

                GroupDataMap.Add("GroupID", OSD.FromUUID(membership.GroupID));
                GroupDataMap.Add("GroupPowers", OSD.FromBinary(membership.GroupPowers));
                GroupDataMap.Add("AcceptNotices", OSD.FromBoolean(membership.AcceptNotices));
                GroupDataMap.Add("GroupInsigniaID", OSD.FromUUID(membership.GroupPicture));
                GroupDataMap.Add("Contribution", OSD.FromInteger(membership.Contribution));
                GroupDataMap.Add("GroupName", OSD.FromString(membership.GroupName));
                NewGroupDataMap.Add("ListInProfile", OSD.FromBoolean(membership.ListInProfile));

                GroupData.Add(GroupDataMap);
                NewGroupData.Add(NewGroupDataMap);
            }

            OSDMap llDataStruct = new OSDMap(3);

            llDataStruct.Add("AgentData", AgentData);
            llDataStruct.Add("GroupData", GroupData);
            llDataStruct.Add("NewGroupData", NewGroupData);

            IEventQueue queue = remoteClient.Scene.RequestModuleInterface <IEventQueue>();

            if (queue != null)
            {
                queue.Enqueue(EventQueueHelper.buildEvent("AgentGroupDataUpdate", llDataStruct), remoteClient.AgentId);
            }
        }
Esempio n. 19
0
        public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);

            if (instance == null)
            {
                return;
            }
            IEventQueue eq = World.RequestModuleInterface <IEventQueue>();

            if (eq == null)
            {
                controllingClient.SendScriptRunningReply(objectID, itemID,
                                                         GetScriptState(itemID));
            }
            else
            {
                eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, GetScriptState(itemID), true),
                           controllingClient.AgentId);
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Enqueues a <see cref="ShutdownRequestEvent"/>.
        /// </summary>
        /// <param name="eventQueue">The <see cref="IEventQueue"/> to use.</param>
        /// <param name="onRequestHandled">An optional delegate invoked sometime after the event finished being handled. It may not get called, if the event queue is suspended or being shut down. Check the return value to know whether you can reasonably expect it.</param>
        /// <param name="file">The source file of the caller.</param>
        /// <param name="member">The method or property name of the caller to this method.</param>
        /// <param name="line">The line number in <paramref name="file"/>.</param>
        /// <returns><c>true</c> if the event was enqueued successfully and you can expect a callback once it's done being handled; otherwise, <c>false</c>.</returns>
        public static bool RequestShutdown(
            this IEventQueue eventQueue,
            Action <ShutdownRequestEvent> onRequestHandled = null,
            [CallerFilePath] string file     = "",
            [CallerMemberName] string member = "",
            [CallerLineNumber] int line      = 0)
        {
            Action <EventBase> action = null;

            if (onRequestHandled.NotNullReference())
            {
                action = e => onRequestHandled((ShutdownRequestEvent)e);
            }

            return(eventQueue.Enqueue(
                       new ShutdownRequestEvent(),
                       action,
                       file,
                       member,
                       line));
        }
        public void QueueEventsToDispatch(TopicConfiguration topicConfiguration, IEnumerable <EventGridEvent> events)
        {
            foreach (var ev in events)
            {
                var eventsToDispatch = GetMatchingSubscriptions(ev, topicConfiguration.Subscriptions)
                                       .Select(s => new DispatchedEvent
                {
                    DispatcherStrategy = s.DispatchStrategy,
                    EndpointUrl        = s.EndpointUrl,
                    Payload            = ev
                }).ToList();

                if (eventsToDispatch.Count == 0)
                {
                    _logger.LogInfo($"No matching subscriptions found for event {ev.Id} (Type: {ev.EventType})");
                }

                foreach (var de in eventsToDispatch)
                {
                    _eventQueue.Enqueue(de);
                }
            }
        }
        void ChatterBoxSessionStartReplyViaCaps(IClientAPI remoteClient, string groupName, UUID groupID, string error)
        {
            if (m_debugEnabled)
            {
                m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
            }

            OSDMap moderatedMap = new OSDMap(4);

            moderatedMap.Add("voice", OSD.FromBoolean(false));

            OSDMap sessionMap = new OSDMap(4);

            sessionMap.Add("moderated_mode", moderatedMap);
            sessionMap.Add("session_name", OSD.FromString(groupName));
            sessionMap.Add("type", OSD.FromInteger(0));
            sessionMap.Add("voice_enabled", OSD.FromBoolean(false));

            OSDMap bodyMap = new OSDMap((error == null)?4:5);

            bodyMap.Add("session_id", OSD.FromUUID(groupID));
            bodyMap.Add("temp_session_id", OSD.FromUUID(groupID));
            bodyMap.Add("success", OSD.FromBoolean(error == null));
            bodyMap.Add("session_info", sessionMap);
            if (error != null)
            {
                bodyMap.Add("error", OSD.FromString(error));
            }

            IEventQueue queue = remoteClient.Scene.RequestModuleInterface <IEventQueue>();

            if (queue != null)
            {
                queue.Enqueue(EventQueueHelper.BuildEvent("ChatterBoxSessionStartReply", bodyMap), remoteClient.AgentId);
            }
        }
        public void SendConsoleOutput(UUID agentID, string message)
        {
            OSD osd = OSD.FromString(message);

            m_eventQueue.Enqueue(EventQueueHelper.BuildEvent("SimConsoleResponse", osd), agentID);
        }
Esempio n. 24
0
 public void Store(string pluginName, AEvent aEvent)
 {
     ququedEventsQueue.Enqueue(pluginName, aEvent);
 }
Esempio n. 25
0
        public void OnTemplateChanged(string templatePath, bool force = false)
        {
            Log.Debug("{0} queued {1}", GenerationType.Template, templatePath);

            ErrorList.Clear();

            var projectItem = _dte.Solution.FindProjectItem(templatePath);

            var template = _templateController.GetTemplate(projectItem);

            if (force == false && ExtensionPackage.Instance.Options.RenderOnSave == false)
            {
                Log.Debug("Render skipped {0}", templatePath);
                return;
            }

            var filesToRender = template.GetFilesToRender();

            Log.Debug(" Will Check/Render {0} .cs files in referenced projects", filesToRender.Count);

            if (Path.GetExtension(templatePath) == Constants.TstXTemplateExtension)
            {
                Task.Delay(1000).ContinueWith(task =>
                {
                    _eventQueue.Enqueue(() =>
                    {
                        var stopwatch = Stopwatch.StartNew();

                        var allProjectFiles = new RootContextImpl(filesToRender.Select(file =>
                                                                                       _metadataProvider.GetFile(file, template.Settings, null)));

                        template.RenderProjectFiles(allProjectFiles);

                        template.SaveProjectFile();

                        stopwatch.Stop();
                        Log.Debug("{0} processed {1} in {2}ms", GenerationType.Template, templatePath,
                                  stopwatch.ElapsedMilliseconds);
                    });
                });
            }
            else
            {
                Task.Delay(1000).ContinueWith(task =>
                {
                    _eventQueue.Enqueue(() =>
                    {
                        var stopwatch = Stopwatch.StartNew();

                        foreach (var path in filesToRender)
                        {
                            var metadata = _metadataProvider.GetFile(path, template.Settings, null);
                            if (metadata == null)
                            {
                                // the cs-file was found, but the build-action is not set to compile.
                                continue;
                            }

                            var file = new FileImpl(metadata);

                            template.RenderFile(file);

                            if (template.HasCompileException)
                            {
                                break;
                            }
                        }

                        template.SaveProjectFile();

                        stopwatch.Stop();
                        Log.Debug("{0} processed {1} in {2}ms", GenerationType.Template, templatePath, stopwatch.ElapsedMilliseconds);
                    });
                });
            }
        }
Esempio n. 26
0
 public async Task <ActionResult <Person> > SignupQueued(int courseId, SignupModel signup, [FromServices] IEventQueue <Signup.Command> queue)
 {
     return(await queue.Enqueue(signup.ToSignupRequest(courseId)) ? new OkResult() : new StatusCodeResult(500));
 }
Esempio n. 27
0
        /// <summary>
        /// Helper function which inserts an Element back on the front of a Queue
        /// </summary>
        /// <param name="eventlist">Queue to insert onto the Front of</param>
        /// <param name="evt">Event to put on the front of the Queue</param>
        private void QueueJump(IEventQueue<IRdfXmlEvent> eventlist, IRdfXmlEvent evt)
        {
            Stack<IRdfXmlEvent> temp = new Stack<IRdfXmlEvent>();
            temp.Push(evt);

            while (eventlist.Count > 0)
            {
                temp.Push(eventlist.Dequeue());
            }

            foreach (IRdfXmlEvent e in temp.Reverse())
            {
                eventlist.Enqueue(e);
            }
        }
Esempio n. 28
0
 public static bool Enqueue <TEvent>(this IEventQueue eventQueue, TEvent @event)
     where TEvent : class, IEventBase
 {
     return(eventQueue.Enqueue(DefaultQueueName, @event));
 }